Java ReentrantReadWriteLock Example

Previous
Next

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:

Read 2 —> Number is 0
Read 1 —> Number is 0
Writer odd is writing
Writer Even is writing
Read 2 —> Number is 0 1 2
Read 1 —> Number is 0 1 2
Writer odd is writing
Writer Even is writing
Read 2 —> Number is 0 1 2 3 4
Read 1 —> Number is 0 1 2 3 4
Writer odd is writing
Writer Even is writing
Read 2 —> Number is 0 1 2 3 4 5 6
Read 1 —> Number is 0 1 2 3 4 5 6
Writer odd is writing
Writer Even is writing
Read 2 —> Number is 0 1 2 3 4 5 6 7 8
Read 2 —> Number is 0 1 2 3 4 5 6 7 8
Read 1 —> Number is 0 1 2 3 4 5 6 7 8
Read 2 —> Number is 0 1 2 3 4 5 6 7 8
Read 1 —> Number is 0 1 2 3 4 5 6 7 8
Read 2 —> Number is 0 1 2 3 4 5 6 7 8
Read 2 —> Number is 0 1 2 3 4 5 6 7 8
Read 1 —> Number is 0 1 2 3 4 5 6 7 8
Read 2 —> Number is 0 1 2 3 4 5 6 7 8
Read 1 —> Number is 0 1 2 3 4 5 6 7 8
Read 2 —> Number is 0 1 2 3 4 5 6 7 8
Read 1 —> Number is 0 1 2 3 4 5 6 7 8
Read 1 —> Number is 0 1 2 3 4 5 6 7 8
Read 1 —> Number is 0 1 2 3 4 5 6 7 8

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.

Previous
Next

Add Comment