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() method. The lookup() method returns a Lookup object, the in() method returns a Lookup object of the specified class—in our case, the Account class—and findVarHandle() generates VarHandle for the attribute we want to access.

Once we have the VarHandle object, we can use different methods to use different access modes. In this example, we used the getAndAdd() method. This method guarantees atomic access to increment the value of the attribute. We pass to them the object we want to access and the value of the increment.

The next section provides more information about the different access modes and the methods you can use in each case.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.78.102