Stormshadow Stormshadow -4 years ago 103
Java Question

Does parking a JAVA thread cause any acquired monitors to be released

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);
}

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download