Avoiding Deadlocks with Lock Ordering and TryLock in Java
This article explains how deadlocks can occur in concurrent transfer scenarios, demonstrates their detection using jstack, and presents two prevention strategies—consistent lock ordering and attempting to acquire all locks with tryLock—while emphasizing the need for distributed locks in real-world systems.
In many concurrent business scenarios, multiple locks are required to protect shared resources, such as a transfer where user A sends money to user B while B simultaneously sends to A. If lock acquisition order is not controlled, a deadlock may occur.
The article shows a simulated deadlock example with two users performing transfers, and explains how after the program runs for a while it stops producing output. Using the jstack tool, the thread state can be inspected to reveal that the process is stuck in a deadlock.
Four classic conditions for deadlock are listed:
Mutual exclusion – resources are exclusive.
Hold and wait – a process holds one resource while waiting for another.
No preemption – held resources cannot be forcibly taken.
Circular wait – a chain of processes each waiting for the next.
To break the circular‑wait condition, the article recommends ordering the locks (lockA before lockB) and provides the following Java code example:
synchronized (lockA) {</code>
<code> synchronized (lockB) {</code>
<code> // transfer logic</code>
<code> }</code>
<code>}Lock ordering is not a universal solution; in more complex scenarios (e.g., A→B, B→C, C→A) the article suggests trying to acquire all required locks atomically using
java.util.concurrent.locks.Lock#tryLock(long, java.util.concurrent.TimeUnit). If any lock cannot be obtained, the operation should be retried.
It also notes that the example uses Java’s built‑in monitor locks, but in distributed environments a distributed lock mechanism must be employed to handle concurrency correctly.
Summary : In concurrent applications that need multiple locks, deadlocks can be avoided by enforcing a consistent lock acquisition order or by attempting to acquire all locks with tryLock and retrying on failure, while ensuring the use of appropriate distributed locks for real‑world scenarios.
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.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
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.
