Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Yield/Join release monitor lock? [duplicate]

Possible Duplicate:
Does thread.yield() lose the lock on object if called inside a synchronized method?

I know Thread.sleep() holds the lock, but Object.wait() releases the lock. Some say yield actually implements sleep(0). Does this mean yield will not release the lock?

Another question. Say the current thread has acquired a lock, and then called anotherThread.join(). Does the current thread release the lock?

like image 394
Sicong Avatar asked Apr 16 '12 14:04

Sicong


2 Answers

Unless the javadoc mentions an object's monitor (such as Object.wait()), you should assume that any locks will continue to be held. So:

Does this mean yield will not release the lock?

Yes.

Does the current thread release the lock?

No.

like image 108
artbristol Avatar answered Sep 23 '22 15:09

artbristol


sleep puts the thread in a wait state, yield returns the thread directly to the ready pool. (So if a thread yields it could go directly from running to the ready pool to getting picked by the scheduler again without ever waiting.) Neither one has anything to do with locking.

From the Java Language Specification:

Thread.sleep causes the currently executing thread to sleep (temporarily cease execution) for the specified duration, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors, and resumption of execution will depend on scheduling and the availability of processors on which to execute the thread.

It is important to note that neither Thread.sleep nor Thread.yield have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to Thread.sleep or Thread.yield, nor does the compiler have to reload values cached in registers after a call to Thread.sleep or Thread.yield.

For example, in the following (broken) code fragment, assume that this.done is a non-volatile boolean field:

while (!this.done)
     Thread.sleep(1000);

The compiler is free to read the field this.done just once, and reuse the cached value in each execution of the loop. This would mean that the loop would never terminate, even if another thread changed the value of this.done.

like image 31
Nathan Hughes Avatar answered Sep 21 '22 15:09

Nathan Hughes