java.­util.­concurrent.­locks.­ReentrantLock Cheat Sheet

September 27, 2016

Category: The package java.util.concurrent

The reentrant lock is a replacement for the easier to use synchronized statement when you need one of the following advanced techniques: lockInterrupibly, tryLock, lock coupling, multiple conditions, or fair locks In the cheat sheet, I have summarized each technique. And in the blog post, I give a detailed description of those techniques.

reentrantlock cheat sheet

Similar as synchronized this lock is reentrant, which means the same thread can acquire the lock multiple times.

Lock Interruptible

private final ReentrantLock lock = new ReentrantLock();
   public void m() throws InterruptedException {
     lock.lockInterruptibly();  
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }

Throws an InterruptedException, when the thread.interrupt method was called by another thread. This allows you to interrupt the processing even while trying to acquire a lock. Something which is not possible with the synchronized statement.

Try Lock

private final ReentrantLock lock = new ReentrantLock();  
   public boolean m() throws InterruptedException {
     if(! lock.tryLock(2 , TimeUnit.MILLISECONDS ) )
     {
       return false; 
     }
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
     return true;
   }

Similar to aqcuireInterrubtable throws a thread interrupted exception when the thread was interrupted by another thread. Additionally, it allows you to give a time span how long to try to acquire the lock. Useful when you have a task which is only valid for a specific amount of time. You can also use it to avoid deadlocks. When you need to acquire two locks simultaneously. Acquire the locks with tryLock. If you can not acquire one of the locks at the given interval release both locks, wait a little bit and try again.

Lock Coupling

The reentrant lock allows you to unlock a lock immediately after you have successfully acquired another lock leading to a technique called lock coupling.This can, for example, be used to lock a linkedlist. You can see an implementation here.

Multiple Conditions

Create:
Condition notFull = lock.newCondition();
Wait for Condition to become true
lock.lock()
{
   while( condition not fullfilled)
   {    
        notFull.await();
   }
}
 finally {
       lock.unlock()
}

Signal that condition has become true

lock.lock() { notFull.signal(); } finally { lock.unlock() }

Be cautious that you do not mix the methods from Condition, 'await', 'signal', with the methods from java.lang.Object wait, notify. Useful when you need to wait for different conditions. ArrayBlockingQueue, for example, uses two conditions one to wait that the queue becomes not full the other to wait till the queue becomes not empty.

Fair locks

private final ReentrantLock lock = new ReentrantLock(true);
Threads get the lock in the order they requested it. This has a high-performance penalty, see the following benchmark for details

Benchmark

synchronized vs. ReentrantLock

The figure shows the throughput of synchronized vs reentrant lock in a fair and unfair mode for different thread counts . The benchmark was run on JDK 8 on an intel i5 4 core CPU using jmh. The source of the benchmark can be downloaded here.

testing multi-threaded applications on the JVM made easy

LEARN MORE

© 2020 vmlens Legal Notice Privacy Policy