Locks

Java 1.5 introduces the Lock interface with its java.util.concurrent package, which contains a lot of concurrency-related classes. It achieves the same goal as that of synchronized but allows you to control manually the scope of the synchronized code.

The performance of Lock and synchronized differs between Java versions, but recent versions have progressed a lot. And generally, if you don't optimize a computing algorithm, choosing one or the other will lead to something close. However, it is generally better to use Lock if the number of concurrent threads accessing the instance is high.

As Lock is an interface, it needs an implementation. The JRE comes with a default implementation called ReentrantLock. Replacing a synchronized block ...

Get Java EE 8 High Performance 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.