synchronized vs ReentrantLock: Which Java Lock Wins in Performance and Flexibility?
This article compares Java's built‑in synchronized keyword with the explicit ReentrantLock class, covering their underlying implementations, performance differences across JDK versions, feature sets such as fairness and interruptibility, lock release mechanisms, and best‑fit scenarios for each approach.
Lock Implementation Methods
synchronized : synchronized is a Java keyword implemented by the JVM. It provides implicit locking without explicit calls, using object‑header flags or monitor locks.
ReentrantLock : ReentrantLock is an explicit lock from java.util.concurrent, relying on OS atomic operations and using lock() and unlock() typically with try/finally blocks.
Performance Comparison
JDK 1.5 and earlier : synchronized had a coarse implementation, resulting in poor performance under contention.
JDK 1.6 and later : Introduced spin locks, lock elision, and lock coarsening, narrowing the performance gap; both mechanisms perform similarly in uncontended scenarios.
Features and Extensibility
synchronized : Simple, non‑fair, automatic release, low risk of deadlock, but lacks fine‑grained control and advanced features.
ReentrantLock :
Interruptible lock waiting : lockInterruptibly() allows a thread to respond to interrupts while waiting for the lock.
Fair vs non‑fair locks : Constructor can specify fairness; synchronized is always non‑fair.
Condition support : Provides Condition with newCondition() for multiple wait queues, unlike synchronized which relies on wait() and notify().
Reentrancy : The same thread can acquire the lock multiple times without deadlocking.
Lock Release Mechanism
synchronized : The JVM automatically releases the lock when exiting the synchronized block or method.
ReentrantLock : Must explicitly call unlock(), usually within a try/finally block to ensure release even on exceptions.
Applicable Scenarios
synchronized : Suitable for simple synchronization needs, low concurrency, and when advanced features like interruptibility or fairness are unnecessary.
ReentrantLock : Ideal for complex synchronization requiring interruptible waits, fairness, condition variables, or high‑concurrency environments.
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.
Xuanwu Backend Tech Stack
Primarily covers fundamental Java concepts, mainstream frameworks, deep dives into underlying principles, and JVM internals.
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.
