Lock vs. Synchronized

We’ve avoided explicit synchronization so far in the examples in this chapter. We can’t escape it for long, however, if we’re going to restrict ourselves to the JDK concurrency API—it’ll show up the minute we have to coordinate changes to multiple variables or multiple objects.

In Java, we have two constructs to acquire locks—the archaic synchronized and its modern counterpart, the Lock interface. The Lock interface gives us more control for locking than the synchronized keyword. Let’s discuss how.


We use synchronized to gain an explicit monitor/lock on objects. While grabbing the monitor and releasing it at the end of the block, it also helps threads cross the memory barrier. However, synchronized is very primitive ...

Get Programming Concurrency on the JVM now with O’Reilly online learning.

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