DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Idempotent Output Keying for Long-Running Tasks During Rolling Deployments
  • Distributed Locking in Cloud-Native Applications: Ensuring Consistency Across Multiple Instances
  • Managing Distributed System Locks With Azure Storage
  • Solving Parallel Writing Issues in MuleSoft With Distributed Locking

Trending

  • AI Agents for Software Engineering and Autonomous Development Workflows
  • Supercharging AI Agents with Azure Context: A Hands-On Guide to Azure MCP
  • Why Your GPU Fleet Is Both Full and Idle: Building a Capacity Orchestration Layer
  • Threat Modeling Context-Aware AI: A STRIDE Walkthrough

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

ReentrantLock Cheat Sheet

This quick and easy guide will show you how to make ReentrantLocks work for you, including examples of some advanced tricks.

By 
Thomas Krieger
·
Updated Oct. 05, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
15.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

The ReentrantLock 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 below, I summarized each technique. And in the rest of this blog post, I give a detailed description of those techniques.

ReentrantLock Cheat Sheet

Similar to synchronized statements, 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() 
    } 
} 

This 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 that 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, this throws a thread interrupted exception when the thread is interrupted by another thread. Additionally, it allows you to give a time span for how long to try to acquire the lock.

This is particularly useful when you have a task that 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 cannot 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()
try { 
    while( condition not fullfilled) { 
        notFull.await(); 
    } 
}
finally { 
    lock.unlock() 
} 

Signal that Condition has become true:

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

Be cautious that you do not mix the methods from Condition, ‘await’, 'signal', with the wait and notify methods from java.lang.Object.

That's 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.

Conclusion

A reentrant lock is one of the advanced techniques used to write multithreaded Java code. Whatever technique you use, you should test the multithreaded part of your application. Read here more about testing multithreaded programs.

Lock (computer science)

Published at DZone with permission of Thomas Krieger. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Idempotent Output Keying for Long-Running Tasks During Rolling Deployments
  • Distributed Locking in Cloud-Native Applications: Ensuring Consistency Across Multiple Instances
  • Managing Distributed System Locks With Azure Storage
  • Solving Parallel Writing Issues in MuleSoft With Distributed Locking

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook