Why Does Java Need Lock When Synchronized Exists? Exploring Deadlock Solutions
The article examines why Java provides the Lock API despite the presence of synchronized, detailing synchronized’s blocking behavior, the risk of deadlocks, and how Lock’s interruptible and tryLock methods offer flexible, non‑blocking alternatives to prevent such deadlocks.
Characteristics of synchronized's lock acquisition
When a thread attempts to acquire a synchronized lock and fails, it enters a blocked state, cannot perform any work, cannot release resources it already holds, and cannot be interrupted; it must wait until another thread releases the lock.
Problems caused by synchronized blocking
The blocking behavior can lead to deadlocks, where two or more threads wait indefinitely for each other’s resources.
A deadlock occurs when two or more threads are each waiting for a lock held by another, creating a circular wait.
Example: Thread 1 locks resource A, Thread 2 locks resource B. Later Thread 1 tries to lock B and blocks, while Thread 2 tries to lock A and also blocks, resulting in a deadlock that cannot be broken because synchronized cannot be interrupted.
How Lock solves the problem
Lock provides APIs that allow a thread to give up acquiring a lock without blocking, or to be interruptible, thus avoiding deadlock.
For instance, if a thread gives up after a timeout, the other thread can acquire the needed lock and progress.
Lock API methods
void lockInterruptibly() throws InterruptedException;This method acquires the lock interruptibly; if the thread is interrupted while waiting, it aborts and throws InterruptedException, allowing the program to continue. boolean tryLock(); Attempts to acquire the lock; if it fails, it returns false immediately without blocking.
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;Tries to acquire the lock, waiting up to the specified time; if the lock is still unavailable, it returns false and can be interrupted.
Lock implementations are built on Java’s AbstractQueuedSynchronizer (AQS), which maintains a state field and a double‑linked queue of waiting threads. ReentrantLock is a common Lock implementation based on AQS.
Summary
Because synchronized blocks and cannot be interrupted, it can cause deadlocks. The Lock interface offers interruptible and non‑blocking acquisition methods, providing flexible ways to avoid such deadlocks.
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.
Sanyou's Java Diary
Passionate about technology, though not great at solving problems; eager to share, never tire of learning!
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.
