Synchronizing a block of code with a lock

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

  • It allows you to structure synchronized blocks in a more flexible way. With the synchronized keyword, you only have control over a synchronized block of code in a structured way. However, the Lock interface allows you to get more complex structures to implement your critical section.
  • The Lock interface provides additional functionalities over the synchronized keyword. One ...

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.