How it works...

In this example, we tested the three modes you can use with a stamped lock. In the Writer task, we get the lock with the writeLock() method (that acquires the lock in write mode). In the Reader task, we get the lock with the readLock() method (that acquires the lock in read mode). Finally, in the OptimisticRead task, first we use tryOptimisticRead() and then we use the validate() method to check whether we can access data or not.

The first two methods, if they can get control of the lock, wait until they get the lock. The tryOptimisticRead() method always returns a value. It will be 0 if we are unable to use the lock and a value different from 0 if we can use it. Remember that in this case, we always need to use the validate() ...

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.