Synchronizing a block of code with a Lock

Java provides another mechanism for the synchronization of blocks of code. It's a more powerful and flexible mechanism than the synchronized keyword. It's based on the Lock interface and classes that implement it (as ReentrantLock). This mechanism presents some advantages, which are as follows:

  • It allows the structuring of synchronized blocks in a more flexible way. With the synchronized keyword, you have to get and free the control over a synchronized block of code in a structured way. The Lock interfaces allow you to get more complex structures to implement your critical section.
  • The Lock interfaces provide additional functionalities over the synchronized keyword. One of the new functionalities is implemented ...

Get Java 7 Concurrency Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.