Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a deadlock possible in this method? How can I prevent it?

Tags:

java

deadlock

public void function(object a, object b){
    synchronized(a){
        synchronized (b){
           a.performAction(b);
           b.performAction(a);
        }
    }
}

Deadlock with 2 Threads? Thanks for the answers!

like image 507
MrBoolean Avatar asked May 25 '15 19:05

MrBoolean


People also ask

How do you know if a deadlock is possible?

Four conditions that must hold for a deadlock to be possible: Mutual exclusion: processes require exclusive control of its resources (not sharing). Hold and wait: process may wait for a resource while holding others. irreversible: unable to reset to an earlier state where resources not held.

What is deadlock explain how deadlock can be prevented?

A deadlock occurs when the first process locks the first resource at the same time as the second process locks the second resource. The deadlock can be resolved by cancelling and restarting the first process.


1 Answers

Sure,

Suppose we have two objects,

Object one = ...;
Object two = ...;

And suppose thread 1 calls:

function(one, two);

While thread 2 calls:

function(two, one);

In thread 1, a == one and b == two, but in thread 2, a == two and b == one.

So while thread 1 is obtaining a lock on object one, thread 2 can be obtaining the lock on object two. Then when each of the threads tries to take the next step, they will be deadlocked.

like image 160
Solomon Slow Avatar answered Oct 07 '22 14:10

Solomon Slow