Holding locks for as short time as possible

Locks, just like other synchronization mechanisms, allow the definition of a critical section that only one thread can execute at a time. You must be very careful to define the critical section. It must only include those instructions that really need mutual exclusion. This is especially true if the critical section includes long operations. If the critical section includes lengthy operations that do not use shared resources, application performance will be worse than it could be.

In this recipe, you will implement an example to see the difference in the performance of a task with a long operation inside the critical section and a task with a long operation outside the critical section.

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.