Lock

Locks are built in Java; every Object has a lock that a thread may acquire when it enters a synchronized block. We discussed that already. In some programming code, there are situations when this kind of structure is not optimal.

In some situations, the structure of locks may be lined up to avoid deadlock. It may be needed to acquire lock A before B and to acquire B before C. However, A should be released as soon as possible, not to prevent access to resource protected by lock D, but also needing lock A before it. In complex and highly parallel structures, the locks are structured many times into trees where accessing a resource a thread should climb down along the tree to a leaf representing the resource. In this climbing, the thread gets hold of a lock on a node, then a lock on a node below it, and then releases the lock above, just like a real climber descending (or climbing up if you imagine the tree with the leafs at the top, which is more realistic, nevertheless graphs usually show trees upside down).

You cannot leave a synchronized block remaining in another that is inside the first one. Synchronized blocks are nested. The java.util.concurrent.Lock interface defines methods to handle that situation and the implementations are also there in the JDK to be used in our code. When you have a lock, you can call the methods lock and unlock. The actual order is in your hand and you can write the following line of code to get the locking sequence:

a.lock(); b.lock(); a.unlock(); c.lock()

The freedom, however, comes with responsibility as well. The locks and unlocks are not tied to the execution sequence of the code, like in case of synchronized block, and it may be very easy to create code that in some case just loses a lock not unlocking it rendering some resource unusable. The situation is similar to a memory leak: you will allocate (lock) something and forget to release (unlock) it. After a while, the program will run out of resource.

My personal recommendation is to avoid using locks if possible and use higher-level constructs and asynchronous communications between threads, such as blocking queues.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.157.197