Daily Archives: August 9, 2021

ConcurrentHashMap

Each segment has multiple entries. Each entry, it starts with a LinkedList. When it has too many, it changes to Black-Red-Tree.

When write, if two writes are for different segment, then it allows. When multiple writes to same segment, it uses CAS(compare-and-set) to write and handle conflict.

Each operation on segment has a counter. The counter only increases. When resize, it will get the counter first. Then it does resize. After resize, compare if the counter changes. If no change, then resize done, if not will do it again. If still fails, it tries to acquire lock on each segment.

 

ReentrantLock, ReentrantReadWriteLock

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();
}