How it works...

If you execute the example, you will see a big difference between the execution time of the two approaches. The task that has all the operations inside the critical section takes longer than the other task.

When you need to implement a block of code protected by a lock, analyze it carefully to only include necessary instructions. Split the method into various critical sections, and use more than one lock if necessary to get the best performance of your application.

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.