How it works...

When you execute the example, you will see how the execution time of the TaskAtomic tasks that use atomic variables are always better than the TaskLock tasks that use locks. You will obtain a similar result if you use the synchronized keyword instead of locks.

The conclusion of this recipe is that utilization of atomic variables will give you better performance than other synchronization methods. If you don't have an atomic type that fits your needs, maybe you can try to implement your own atomic type.

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.