Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does below java multi-threads example always deadlock

Object o1 = new Object();
Object o2 = new Object();

Thread1:

synchronized(o1){
    Thread.sleep(1000);
    synchronized(o2){
      //do something
    }
}

Thread2:

synchronized(o2){
    Thread.sleep(1000);
    synchronized(o1){
      //do something
    }
}

Test code:

new Thread1().start();
new Thread2().start();

does above code always deadlock, if not, why?

like image 586
Tony Avatar asked Dec 13 '25 14:12

Tony


1 Answers

Yes, because once a thread wakes up, it will not be able to enter the next synchronized section because the lock is already taken.

(There could be a theoretical scenario where there will not be a deadlock - if one thread gets both locks before second thread got cpu time to even get the first lock)

like image 83
Yigal Avatar answered Dec 15 '25 07:12

Yigal