Week 99 — What is the `ReentrantReadWriteLock` class used for and how can it be used?

Question of the Week #99
What is the ReentrantReadWriteLock class used for and how can it be used?
2 Replies
dan1st
dan1st2mo ago
sample answer:
0x150
0x1502mo ago
A ReadWriteLock consists of two locks: One for reading and one for writing. The goal of it is that multiple threads can hold the read-lock concurrently but only one can hold the write-lock and only while no thread is holding the read-lock. If a a thread owns the read lock, the write lock cannot be obtained by any other thread and vice-versa. ReentrantReadWriteLock is an implementation of the ReadWriteLock interface that allows threads to obtain the lock even if they already have it.
private final ReadWriteLock LOCK = new ReentrantReadWriteLock();

//This method can run concurrently as often as needed but not concurrently with doWrite() (one has to wait for the other to finish)
public void doRead(){
Lock readLock = LOCK.readLock();
readLock.lock();
try{
//perform some read operation
} finally {
readLock.unlock();
}
}

//This method cannot run concurrently. While this method is running, other threads have to wait for the lock.
public void doWrite(){
Lock writeLock = LOCK.writeLock();
writeLock.lock();
try{
//perform some write operation
} finally {
writeLock.unlock();
}
}
private final ReadWriteLock LOCK = new ReentrantReadWriteLock();

//This method can run concurrently as often as needed but not concurrently with doWrite() (one has to wait for the other to finish)
public void doRead(){
Lock readLock = LOCK.readLock();
readLock.lock();
try{
//perform some read operation
} finally {
readLock.unlock();
}
}

//This method cannot run concurrently. While this method is running, other threads have to wait for the lock.
public void doWrite(){
Lock writeLock = LOCK.writeLock();
writeLock.lock();
try{
//perform some write operation
} finally {
writeLock.unlock();
}
}

Did you find this page helpful?