Deadlock in Java is a condition where two or more threads are blocked forever, each waiting for the other to release a lock. This occurs primarily in a multithreaded environment when synchronized resources are used in such a way that a circular wait condition arises. Understanding and preventing deadlocks is crucial for building efficient and bug-free Java applications.
🔁 What Causes Deadlock in Java?
Deadlock occurs when the following four conditions are met simultaneously:
- Mutual Exclusion: At least one resource must be held in a non-shareable mode.
- Hold and Wait: A thread holding at least one resource is waiting to acquire additional resources held by other threads.
- No Preemption: Resources cannot be forcibly removed from threads holding them.
- Circular Wait: A set of threads are each waiting for a resource that the next thread in the cycle holds.
Note: All four conditions must be true for a deadlock to occur. Removing any one can prevent deadlock.
🧵 Java Deadlock Code Example
Let’s look at a simple code example that demonstrates a classic deadlock scenario:
class SharedResource {
void methodA() {
synchronized (String.class) {
System.out.println(Thread.currentThread().getName() + " locked String.class");
synchronized (Integer.class) {
System.out.println(Thread.currentThread().getName() + " locked Integer.class");
}
}
}
void methodB() {
synchronized (Integer.class) {
System.out.println(Thread.currentThread().getName() + " locked Integer.class");
synchronized (String.class) {
System.out.println(Thread.currentThread().getName() + " locked String.class");
}
}
}
}
public class DeadlockExample {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread t1 = new Thread(() -> resource.methodA(), "Thread-1");
Thread t2 = new Thread(() -> resource.methodB(), "Thread-2");
t1.start();
t2.start();
}
}
In the code above:
Thread-1locksString.classand waits forInteger.class.Thread-2locksInteger.classand waits forString.class.
This creates a circular wait and results in a deadlock.
⚠️ How to Detect Deadlocks in Java?
Deadlocks can be hard to detect manually. Java provides several tools:
- jconsole – A Java monitoring tool.
- jstack – Prints Java thread stack traces for a Java process.
- VisualVM – Graphical interface to monitor JVM.
Using jstack:
jstack <pid> | grep -A 30 "Found one Java-level deadlock"
This command identifies deadlocked threads and shows the locks they are holding or waiting for.
💡 How to Prevent Deadlocks in Java?
Several techniques can help prevent deadlocks in Java:
1. Lock Ordering
Always acquire locks in a consistent global order.
synchronized (String.class) {
synchronized (Integer.class) {
// do something
}
}
Ensure that all threads follow this same lock order.
2. Try-Lock with Timeout
Use ReentrantLock.tryLock() with timeout to avoid indefinite waiting.
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.TimeUnit;
public class TryLockExample {
private static ReentrantLock lock1 = new ReentrantLock();
private static ReentrantLock lock2 = new ReentrantLock();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
try {
if (lock1.tryLock(1, TimeUnit.SECONDS)) {
Thread.sleep(500);
if (lock2.tryLock(1, TimeUnit.SECONDS)) {
System.out.println("Thread 1 acquired both locks");
lock2.unlock();
}
lock1.unlock();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(() -> {
try {
if (lock2.tryLock(1, TimeUnit.SECONDS)) {
Thread.sleep(500);
if (lock1.tryLock(1, TimeUnit.SECONDS)) {
System.out.println("Thread 2 acquired both locks");
lock1.unlock();
}
lock2.unlock();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
}
}
This technique prevents deadlock by avoiding waiting forever for a lock.
3. Avoid Nested Locks
Minimize the use of nested synchronized blocks. If not necessary, don’t acquire multiple locks simultaneously.
4. Use Higher-Level Concurrency Utilities
Prefer classes from java.util.concurrent like Semaphore, ExecutorService, etc., which provide better control and abstraction.
📊 Real-World Scenario Example
Let’s simulate a banking scenario where deadlock may occur if accounts try to transfer money simultaneously:
class Account {
private int balance = 1000;
public void withdraw(int amount) {
balance -= amount;
}
public void deposit(int amount) {
balance += amount;
}
public int getBalance() {
return balance;
}
}
class Transfer {
public void transferMoney(Account from, Account to, int amount) {
synchronized (from) {
synchronized (to) {
from.withdraw(amount);
to.deposit(amount);
}
}
}
}
public class BankDeadlock {
public static void main(String[] args) {
Account acc1 = new Account();
Account acc2 = new Account();
Transfer transfer = new Transfer();
Thread t1 = new Thread(() -> transfer.transferMoney(acc1, acc2, 100));
Thread t2 = new Thread(() -> transfer.transferMoney(acc2, acc1, 200));
t1.start();
t2.start();
}
}
This program might deadlock because t
Feeling lucky? I jumped on Luckygame and haven’t looked back. Easy to use, and the games are pretty fun. Give it a shot if you fancy a little gamble! Test your luck at luckygame.
Betcriscasino keeps popping up. Might give betcriscasino a shot this weekend, see if it lives up to the buzz.
Playmexico is on my radar. Gotta see if playmexico offers the games and odds I’m after.
We’re a gaggle of volunteers and starting a new scheme in our community. Your website offered us with helpful info to work on. You’ve done an impressive job and our whole group will probably be thankful to you.
Hands down one of the best online casinos I have tried recently. The promotions are actually fair and not just bait. Highly recommend it to everyone. pk777betonlinecasino
Really impressed with the security and the variety of payment methods available here. It makes depositing and withdrawing so much easier. bd335casino
Just love the vibe of this platform. The games are exciting and the bonuses keep me coming back for more. A solid choice for any gamer. gameus88
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
А обычные таблетки не помогали. Но ничего не работало, ему становилось только хуже. Позвонила, объяснила ситуацию, и мне сказали, что врач будет через час. Капельница от похмелья — это вернуло мужа в нормальное состояние. Вечером он был полностью в порядке. Цена оказалась вполне разумной. капельница от похмелья в мытищах https://alkogolizm.kapelnicza-ot-pokhmelya-uzao.ru По ссылке — подробная информация для Подмосковья. Звоните, помогайте, спасайте. Капельница от похмелья — это реальная помощь, которая работает!
I gotta bookmark this website it seems very useful very helpful
I truly appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thank you again
Great platform with a very intuitive layout. I love how easy it is to navigate through the different sections. asiabetlogin makes everything so much simpler for the user.
Such a vibrant community and the bonuses for new members are actually generous. Feeling like a real VIP at vipphfunclub
Had a great experience with the bonuses here. The registration process was a breeze and I started winning almost immediately. Check out win96jiliph if you want a fair game.
Best betting experience I have had in a while. The odds are fair and the customer support team is actually helpful. You guys should try 888fbbet.
Straightforward and reliable. I appreciate how they handle customer support. Everything is sorted quickly at wr777login.
The Asian market options here are fantastic. Very inclusive and the rewards system is quite generous. I’m sticking with phplus777asia from now on.
The login process is seamless and the customer support is surprisingly responsive. It is a very trustworthy site. Log in via vnnk88dangnhap today.
Finally found a place that doesn’t glitch out during the big wins. The login process is seamless and the support team is actually helpful. Love d333betlogin.
[2904]winnersbet Official Login | Online Slots & GCash Bonus PH,winnersbet offers a seamless app download for top online slots. Claim your GCash casino bonus and learn how to play baccarat today. Join the action now! visit: winnersbet
[1985]Xsmtrung | Đăng nhập tải app và chơi nổ hũ baccarat,Truy cập xsmtrung để đăng nhập và tải app nhanh chóng. Trải nghiệm game slot nổ hũ hấp dẫn, tìm hiểu luật chơi baccarat online và nạp tiền qua momo dễ dàng. visit: xsmtrung