Mastering Java’s Synchronized Reentrant Lock: Features, Pitfalls, and Best Practices
This article explains Java’s synchronized keyword’s reentrant lock capability, demonstrates how nested synchronized methods acquire the same lock without deadlock, explores additional features such as automatic lock release on exceptions, using arbitrary objects as monitors, and illustrates the double‑checked locking pattern for singleton implementation.
Synchronized Reentrant Lock
The Synchronized keyword in Java provides a reentrant lock, meaning that if a thread already holds an object's lock, it can acquire the same lock again without blocking.
When a thread requests a lock held by another thread, it blocks; however, if it requests a lock it already holds, the request succeeds because the lock is reentrant.
A simple example shows that a method synchronized on an object can call another synchronized method of the same class and still obtain the lock. method1() calls method2() while holding the lock on syncDubbo, avoiding deadlock.
Without reentrancy, the second lock request would block, leading to deadlock. This is illustrated in the following diagram:
The execution result is shown below:
Reentrant locks prevent deadlocks in scenarios such as validating a password stored in a local file, where the password verification method (synchronized) is called from the password update method (also synchronized).
For deeper implementation details, refer to external resources.
Other Features of Synchronized
1. Automatic lock release on exceptions
If a thread throws an exception while holding a synchronized lock, the lock is automatically released. The following diagram demonstrates this behavior:
Resulting output shows that the program stops execution after the error, and the lock is freed.
2. Using any object as a monitor
Java allows any object to serve as a monitor for synchronized blocks. The illustration below shows this capability:
3. Singleton pattern – Double‑checked locking
The classic double‑checked locking implementation for a singleton uses synchronized to ensure thread‑safe lazy initialization. The code example is depicted below:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
