Java ReentrantReadWriteLock Example


In this tutorial, we will see ReentrantReadWriteLock Example. ReentrantReadWriteLock supports semantics of ReentrantLock and also ReadWriteLock.
ReadWriteLock has two locks, one for read and one for write. Request for read lock from multiple threads can be acquired if there is no write request. If there is a write request, no other thread will be able to acquire read or write lock on that resource.

ReentrantReadWriteLock example:

It is an implementation of ReadWriteLock interface.

It has two kinds of locks i.e. ReaderLock and WriterLock.

Let’s understand it with the help of an example:
We will have three runnable interfaces. Reader, WriterEven and WriterOdd.
Reader: It will read number variable.
WriterEven: It will write even digit to the number.
WriterOdd: It will write odd digit to the number.
We are going to use ReentrantReadWriteLock with fairness as true.

When you run program, you will get below output:

As you can see, Reader threads are blocked when writer threads have acquired writeLock and also if writerEven has acquire writeLock then writerOdd won’t able to acquire writerLock until writerEven releases it or vice versa.
lock.readLock().lock() : It is used to request for readLock.
lock.readLock().unlock() : It is used to release readLock.
lock.writeLock().lock() : It is used to acquire writeLock.
lock.writeLock().unlock() : It is used to release writeLock.


Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog