ReentrantLock, ReentrantReadWriteLock

By | August 9, 2021
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

RentrantLock is almost the same as synchronized keyword. Only difference is that synchrnozied keyword needs a block. It maintains a queue for the threads.

RentrantLock lock = new ReentrantLock();

lock.lock();
try {
    do something..
} finally {
    lock.release();
}

ReentrantReadWriteLock. It also maintains a queue for threads. When it has queue:
[readThread1, readThread2, writeThread3, readThread4]

When it is released, readThread1, readThread2 can read the resource concurrently. However, readThread4 will be blocked, until writeThread3 finishes the write.

ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
ReentrantReadWriteLock.WritLock writeLock = lock.writeLock();

private void readResource() {
    readLock.lock();
    // read
    readLock.unlock();
}

private void writeResource() {
    writeLock.lock();
    // write
    writeLock.unlock();
}