Deadlock in Java

When we talk about threads, Deadlock is another important thing. If you are a beginner, this may be very useful when you face an interview.

What is called Deadlock?

Deadlock is caused by multiple threads are blocked and waiting for each other to release the lock of the object.

At the time they are waiting for each other forever. Look at the following code. Then you may understand it.

Sometimes it looks complex, but it is easy to understand. When you run this, you may get one of the following results.

ThreadOne s1 
ThreadTwo s2 


ThreadOne s2
ThreadTwo s1

Deadlock is critical  

It is very difficult to test for deadlocks. You may know that testing a multithreaded application is a very difficult task. This the main disadvantage of using threads. Then you can understand the situation with Threads + Deadlocks. 

Because deadlocks depend on the system, environment, underlying hardware, etc.

What does caused for deadlocks?

Mainly deadlocks are caused by inconsistent lock ordering of objects. If you have any idea to detect deadlocks it may help you to prevent deadlocks.

How to prevent a deadlock?

  • Use multi-threads, only if it is a must
As you know, if you use multi-threads; it makes your code more complex. So you can choose multi-threading only if you want in your application.

  • Order locks
If you can arrange your locks according to an order, then it will avoid conflicts with each lock. So what you can do is; assign a numeric value to each lock and you should order them according to the priority of those locks. 

But you should have a good understanding of locks and when they are needed from each other.

  • Set a lock timeout 
You can set timeout to remove conflicts between locks. You can build the mechanism to rebuild the application for random timing if it detects a deadlock. Then it will run continuously without giving any chance to deadlocks. 

  • Keep lock private (Encapsulate locks)
Make locks private, then complete control is in your hand. Don't share data between threads if it is not necessary.

  • Look for other alternative ways
You can use volatile fields, then it doesn't require a lock and multiple threads can access the latest value of the field.

  • Focus about deadlocks in application design time
This may help to avoid deadlocks because deadlocks are unpredictable sometimes. If you study more about the system in design time it may help you to avoid deadlocks.

  • Always try to shrink synchronization blocks or methods

This may help to make your design easier to it will make easy to understand potential deadlocks. Because it is easy to check in smaller blocks rather than huge blocks.

Deadlock in Java Deadlock in Java Reviewed by Ravi Yasas on 10:01 PM Rating: 5

1 comment:

  1. Useful info. Lucky me I discovered your site unintentionally, and I am shocked why this twist of fate didn't came about earlier!
    I bbookmarked it.


Powered by Blogger.