How to Avoid Deadlock in JavaIn Java, deadlock is a part of multithreading. The multithreading environment allows us to run multiple threads simultaneously for multitasking. Sometimes the threads find themselves in the waiting state, forever that is a deadlock situation. The deadlock is a situation when two or more threads try to access the same object that is acquired by another thread. Since the threads wait for releasing the object, the condition is known as deadlock. The situation arises with more than two threads. The question how to avoid deadlock in Java is the most important and popular question asked in a Java interview. In this section, we will learn how to detect and avoid deadlock in Java. What is deadlock in Java?In the thread, each object has a lock. To acquire a lock, Java provides synchronization to lock a method or code block. It allows that at a time only one thread can access that method. Nevertheless, if a thread wants to execute a synchronized method it first tries to acquire a lock. It is possible that another thread has already acquired that lock then the thread (that wants to acquire the lock) will have to wait until the previous thread does not release the lock. Let's understand it through an example. ExampleSuppose, there are two threads A and B. The thread A and B acquired the lock of Object-A and Object-B, respectively. Assume that thread A executing method A and wants to acquire the lock on Object-B, while thread B is already acquired a lock on Object-B. On the other hand, thread B also tries to acquire a lock on Object-A, while thread A is acquired a lock on Object-A. In such a situation both threads will not complete their execution and wait for releasing the lock. The situation is known as, deadlock. ![]() How to detect deadlock in Java?There are following ways to detect a deadlock:
Consider a situation when two bank accounts trying to transfer money to each other at the same time. It means that one account is debited and another account is credited, and vice-versa. Let's implement the situation in a Java program. In the following example, we can easily detect a deadlock. Because two threads are sending money to each other at the same time that leads to a deadlock situation. Account.java In the above example, there are two threads that are attempting to transfer money to each other at the same time. It creates a deadlock situation because the threads try to acquire the lock in the reverse order. How to avoid deadlock in Java?Although it is not possible to avoid deadlock condition but we can avoid it by using the following ways:
Let's understand it through an example. AvoidDeadlockExamplet.java Output: ![]() We recommend you that if you are dealing with multiple locks, always acquire the locks with lower numerical value before acquiring the locks with a higher numeric value.
Next TopicJava Tutorial
|