Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Deadlock prevention
2.1.
Eliminate Mutual Exclusion 
2.2.
Eliminate Hold and wait
2.3.
Eliminate No Preemption 
2.4.
Eliminate Circular Wait 
3.
Deadlock Avoidance
3.1.
Example
4.
Frequently Asked Questions
4.1.
How do you detect deadlock in Java?
4.2.
What is Deadlock in Java?
4.3.
What is multi-threading in Java?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Deadlock Prevention and Avoidance

Author Shivam Verma
0 upvote

Introduction

Before knowing about deadlock prevention and avoidance, we have to know what a deadlock is? Deadlock in Java is a part of multi-threading. It is a programming situation that occurs when two or more threads wait for each other to release the resource(lock) they need and get stuck for an infinite time.

Also Read About, Multithreading in java Multithreading Operating System, and Open Source Operating System

Deadlock prevention

Deadlock can be prevented by removing any of the four conditions listed below.

  1. Mutual Exclusion
  2. Hold and Wait
  3. No preemption
  4. Circular wait

Eliminate Mutual Exclusion 

We cannot prevent deadlocks by denying the mutual exclusion condition because some resources, such as the tape drive and printer, are inherently non-shareable.

Eliminate Hold and wait

When a process holds a resource while also waiting for another resource to complete its execution, this is known as a hold and wait condition. If we don't want this scenario to happen, we need to ensure that when a process requests a resource, it doesn't have any other resources. 

There are some protocols that can be utilized to prevent the Hold and Wait scenario from occurring:

  1. According to the first protocol, Allocate all required resources to the process before the beginning of its execution, but it will lead to low device utilization
  2. The second protocol permits a process to make a new request for resources after releasing the current set of resources, but this solution may lead to starvation.

Eliminate No Preemption 

Preempt resources from the process when other high-priority processes require resources. 

Eliminate Circular Wait 

A numerical number will be allocated to each resource. A process may request that the number of resources be increased or decreased. For Example, if process P1 is given R5 resources, the next time process P1 requests R4, R3, or any other resource less than R5, the request will be denied. Only requests for resources more than R5 will be granted.

You can also read about the Multiple Inheritance in Java.

Deadlock Avoidance

Although it is not possible to avoid the deadlock condition, we can prevent it by using the following methods:

  • Avoid nested locks: A deadlock in Java mainly happens when we provide multiple locks to multiple threads. So avoid giving a lock to multiple threads if we have already given to one.
  • Avoid unnecessary locks: We should always try to avoid providing unnecessary locks to threads. We must use locks only for those members on which it is required.
  • Using Thread.join() Method: There are chances of a deadlock condition when one thread waits for another to complete the execution. If a deadlock condition occurs, we can use thread.join() with the maximum time the execution will take.
  • Lock Time-out: We can prevent a deadlock by using the time-out condition if a thread does not acquire a lock within a specific time.
  • Use Lock Ordering: In this method, each lock has a numeric value, and if we acquire the locks with a lower numeric value before those with a higher numeric value, we can avoid a deadlock situation.

Here is an example for a better understanding.

Example

class AvoidDeadlock
{
    public static void main(String[] args) throws InterruptedException
    {
        final String objt1="Object1";
        final String objt2="Object2";
        final String objt3="Object3";
        Thread th1=new Thread(new SynchroniseThread(objt1, objt2), "th1");
        Thread th2=new Thread(new SynchroniseThread(objt2, objt3), "th2");
        th1.start();
        Thread.sleep(1000);
        th2.start();
        Thread.sleep(1000);
    }
}
class SynchroniseThread implements Runnable
{
    private Object objt1;
    private Object objt2;
    public SynchroniseThread(Object ob1, Object ob2)
    {
        this.objt1=ob1;
        this.objt2=ob2;
    }
    @Override
    public void run()
    {
        String thread_name=Thread.currentThread().getName();
        System.out.println(thread_name+" acquiring the lock on "+objt1);
        synchronized (objt1)
        {
            System.out.println(thread_name+" acquired the lock on "+objt1);
            try
            {
                Thread.sleep(2000);
            }
            catch(InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        System.out.println(thread_name+" released the lock on "+objt1);
        System.out.println(thread_name+" acquiring the lock on "+objt2);
        synchronized (objt2)
        {
            System.out.println(thread_name+" acquired the lock on "+objt2);
            try
            {
                Thread.sleep(2000);
            }
            catch(InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        System.out.println(thread_name+" released the lock on "+objt2);
   }
}

Output

th1 acquiring the lock on Object1
th1 acquired the lock on Object1
th2 acquiring the lock on Object2
th2 acquired the lock on Object2
th1 released the lock on Object1
th1 acquiring the lock on Object2
th2 released the lock on Object2
th1 acquired the lock on Object2
th2 acquiring the lock on Object3
th2 acquired the lock on Object3
th1 released the lock on Object2
th2 released the lock on Object3

 

Try it by yourself on java online compiler.

Frequently Asked Questions

How do you detect deadlock in Java?

We can detect if a deadlock condition has occurred in Java by running the program in CMD. The command depends upon the OS type and Java version. Using the command, we can collect the thread dumps to analyze the root cause of the deadlock situation. If we are running Java 8 on windows, a command would be jcmd $PID Thread.print.
 

What is Deadlock in Java?

Deadlock in Java is a programming situation that occurs when two or more threads wait for each other to release the resource(lock) they need and get stuck for an infinite time.
 

What is multi-threading in Java?

Multi-threading is a Java feature that allows simultaneous execution of multiple threads for maximum CPU utilization. A thread is a lightweight sub-process, the smallest unit of processing.

Conclusion

In this article, we have extensively discussed Deadlock Prevention and Avoidance in the java programming language. We also discussed How to avoid deadlock in Java with the help of an example.

Recommended Readings:

We hope that this blog has helped you enhance your knowledge regarding Deadlock Prevention and Avoidance and if you would like to learn more, check out our article on Assignment Operator. You can read our Java language articles by clicking Java Archives

Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass