Aaron Shaw
Aaron Shaw

Reputation: 45

Does DynamoDB support pessimistic locking?

updated

Original question below - revised question is this:

Ignoring my use case below, using dynamo can one do an old fashioned pessimistic lock whereby the entire item is locked for concurrent access until I am done with it?


Quick question, as per title - all my googling only shows talk of optimistic locking.

Would like to know if it's possible to simply do the equivalent of a 'select for update'?

Use case requires a read, then to update a modified version. Would be nice to do a single read and a single write, rather than 2 reads and a write required for the optimistic strategy.

Thanks.

Upvotes: 2

Views: 7912

Answers (1)

Peter Branforn
Peter Branforn

Reputation: 1677

The locking of 'items' is provided as a client side extension in the Java SDK, you need to do some work to actually make use of it.

The reason for this is the distributed nature of the dynamo DB. Note that the lock is not a classic 'row based' lock on the 'server side'. The lock must be obeyed by the clients using the related 'items'.

The client side class to manage a lock is called 'AmazonDynamoDBLockClient'. If you search for this class you will find examples on using it from amazon SDK developers.

Things that are required to do with it:

  • Add a global ID for a lock to ask before writing an 'item'
  • Make the writer aware of locks and prevent writing in case it is 'active'
  • Timeout the lock, so that in case a client dies the lock gets released

Taken right from such a sample:

    //build a lock client. any other client _not_ using this _same_ lock
    //can still modify the data! this is not 'safe' in this regard!
    final AmazonDynamoDBLockClient client = new AmazonDynamoDBLockClient(
        AmazonDynamoDBLockClientOptions.builder(dynamoDB, "customLockTable")
                .withTimeUnit(TimeUnit.SECONDS)
                .withLeaseDuration(100L)
                .withHeartbeatPeriod(40L)
                .withCreateHeartbeatBackgroundThread(createHeartbeatBackgroundThread)
                .build());
    //try to acquire a lock on the partition key "FirstPart"
    //of course this can fail, since someone else could have the lock
    final Optional<LockItem> lockItem =
            client.tryAcquireLock(AcquireLockOptions.builder("FirstPart").build());

For the above code to work you need to create a specific 'customLockTable', this is not part of the DB backend by nature. Therefore the above sample is incomplete!

Upvotes: 4

Related Questions