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.

synchronized

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 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.