Reputation: 7179
When thread execution is suspended by parking a thread, does it cause the thread to relinquish ownership of any acquired object monitors?
Put simply, can the following code deadlock if a thread (t1) acquires the monitor for the 'this' object and is parked while another thread (t2) that tries to unpark t1 by first trying to acquire the monitor of 'this' and blocking.
// Thread t1 executes this code first.
syncronized(this) {
LockSupport.park();
}
// Thread t2 then executes this piece of code.
synchronized(this) {
LockSupport.unpark(t1);
}
Upvotes: 5
Views: 367
Reputation: 27190
That would make no sense.
Sometimes a thread needs to hold more than one lock at a time. Some awful piece of legacy code might do something like this:
synchronized(objectA) {
lockB.lock();
try {
doSomethingThatRequiresOwnershipOfBothLocks();
} finally {
lockB.unlock();
}
}
It would not solve any problems if the lockB.lock()
call temporarily unlocked the monitor on objectA.
Upvotes: 0
Reputation: 937
There will be a deadlock because t1
is blocked and still owns lock on this
object when t2
is trying to acquire the same lock.
Upvotes: 4