Reputation: 117
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?
Upvotes: 3
Views: 72
Reputation: 27190
The correct answer is "No."
The sleep()
calls make it extremely likely that the two threads will deadlock, but they do not guarantee that the two threads will deadlock.
Your "test code" thread starts the "thread1" and "thread2" threads like so:
new Thread1().start();
new Thread2().start();
If the two threads start within one second of each other, then you'll get a deadlock. But there's no guarantee that it will come out that way. Here's one possible serialization:
test code thread1 thread2
--------- ------- -------
new Thread1
.start()
... lock o1
... sleep(1000)
new Thread2 ...
.start() ... waiting to run
lock o2 ...
do something block on o2
unlock o2 ...
unlock o1 lock o2
sleep(1000)
lock o1
do something
unlock o1
unlock o2
Why did thread2 wait so long before attempting to lock o2? Who knows? Maybe the system was heavily loaded with other processes. The point is, it's very unlikely to happen in this way, but it could happen. Therefore, your example is not guaranteed to always deadlock.
Upvotes: 1
Reputation: 2689
Call Thread1 A
and Thread2 B
. A1
means the first thread has locked on o1
etc. Possible sequences of operation are
A1:A2:B2:B1
A1:B2 - deadlock on steps A2 and B1
B2:A1 - deadlock on steps B1 and A2
B2:B1:A1:A2
So the code will not deadlock if one thread completes its operation before the second thread executes its first synchronized
block. When either thread executes is controlled by the system scheduler.
Upvotes: 1
Reputation: 266
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)
Upvotes: 2