Saturday, June 11, 2022

Java: wait & notify, await & signal, park & unpark

There are several way to stop a thread in Java, to get awaken later. Here are their usages:

wait & notify

Every object has a .wait() and .notify() method. These methods must be called in a synchronized block. 

When a .notify() happened before .wait(), it will not awake the thread.

await & signal 

With ReentrantLock, a condition object can be pulled from the lock, by `lock.newCondition()`. When the lock is locked, .await() These methods needs to be call when the lock is in lock state.

When a .signal() happened before .await(), it will not awake the thread.

LockSupport: park & unpark

Unlike wait & await, LockSupport.park() and LockSupport.unpark(t) and doesn't need to be in a locked / synchronized block. Since LockSupport is permit based, unpark assign a permit to a thread, which can be later used in park . So the order of park and unpark is not strict. Notice that permit doesn't have a counter - it can only be used in 1 park call.


Thursday, June 09, 2022

Java Locks: synchronized. ReentrantLock, ReentrantReadWriteLock, StampedLock

synchronized vs. ReentrantLock

Both create critical sections. ReentrantLock is unstructured and can lock and unlock in different methods. ReentrantLock can tryLock with a timeout.

ReentrantLock vs ReentrantReadWriteLock

ReentrantLock creates a critical sections that blocks both read & write. ReentrantReadWriteLock allows readLocks to read together, while blocking by critical sections when write is involved. Note that since readLock can block writeLock, it could result in writeLock starvation when a lot of readLocks appear. WriteLock cannot proceed until all readLocks are unlocked.

ReentrantReadWriteLock vs. StampedLock

ReentrantReadWriteLock is a pessimistic lock, which doesn't read while writer writes, and stops writer when it reads.

StampedLock is an optimistic lock, which reads (by tryOptimisticRead) while allowing write to happen, but also detects write (by validate) - if write happens during the time, simply reads again.