10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

THREADS AND LOCKS Sleep and Yield 17.9<br />

17.9 Sleep and Yield<br />

Thread.sleep causes the currently executing thread to sleep (temporarily<br />

cease execution) for the specified duration, subject to the precision and accuracy<br />

of system timers and schedulers. <strong>The</strong> thread does not lose ownership of any monitors,<br />

and resumption of execution will depend on scheduling and the availability<br />

of processors on which to execute the thread.<br />

Neither a sleep for a period of zero time nor a yield operation need have<br />

observable effects.<br />

It is important to note that neither Thread.sleep nor Thread.yield have<br />

any synchronization semantics. In particular, the compiler does not have to flush<br />

writes cached in registers out to shared memory before a call to Thread.sleep or<br />

Thread.yield, nor does the compiler have to reload values cached in registers<br />

after a call to Thread.sleep or Thread.yield.<br />

DISCUSSION<br />

For example, in the following (broken) code fragment, assume that this.done is a non-volatile<br />

boolean field:<br />

while (!this.done)<br />

Thread.sleep(1000);<br />

<strong>The</strong> compiler is free to read the field this.done just once, and reuse the cached value<br />

in each execution of the loop. This would mean that the loop would never terminate, even if<br />

another thread changed the value of this.done.<br />

DRAFT<br />

583

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!