JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Java ReentrantReadWriteLock Example

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.

.