How it works...

The following screenshot shows the output of an execution of the application:

As you make the same number of increment and decrement operations, the expected result in both cases is 0. We obtain this result with the amount attribute because as we access it using the VarHandle, we guarantee atomic access to its modifications. On the other hand, the unsafeAmount doesn't have the expected value. Access to this value is not protected and we have a data-race condition.

To use a variable handle, first we have to obtain it using the lookup() method of the MethodHandles class, followed by the in() method and then the findVarHandle() ...

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.