views:

186

answers:

3

Hi Guys,

It is mentioned that one of the advantages of Lock (java.util.concurrent.locks.Lock) over intrinsic lock is that Lock facilitates "chain locking". Chain locking being, hold a lock for A, then acquire B, after acquiring B release A and then acquire C ...

I am just curious, have you guys encountered any situation in which the use of chain locking was necessary?

Cheers, Vic

+3  A: 

Any situation where you have a series of critical sections which are mutually independent, but you wish to execute in order would be appropriate.

Think of this like a burrito bar, you have a queue of consumers, and four or so workers on the other side. You don't want any consumers to skip ahead of others, nor do you want any of the workers to serve more than one consumer at a time. You could create queues between each server, however you know that the pipeline is strictly sequential, and sometimes that abstraction isn't the best representation in code.

HOWEVER, you may have exceptional handling where you want to be able to acquire one of the stages of the pipeline. E.g., the cashier at the end. If someone comes in for a gift-card, they could skip the queue and go straight to the cashier. This model reduces average wait times/latency, while providing the necessary locks and sequencing guarantees for other workers.

As with anything in computing, there are many ways to achieve the same effect, however the cognitive distance between the domain model and the implementation model impacts code clarity. Therefore if you have an application where you want to ensure that you don't release one resource before you have acquired the next in the sequence, a lock chain is a convenient solution.

Finally, don't forget that the synchronized capability of java is strictly nested, you can only release a lock in the order you acquired it. Not ideal if you have long complicated pipelines.

caskey
A: 

A lock chain could be used to enforce a lock-ordering policy. I.e. that lock B can only be acquired if you have lock A already.

This is to prevent deadlocks where a client has B but not A and another has the reverse situation - the old deadly embrace.

daveb
A: 

Does anybody have an code snippet example, using java.util.concurrent.locks.Lock, for "chain-locking"?

Loop