O'Reilly logo

Java 9 Concurrency Cookbook - Second Edition by Javier Fernández González

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required