I
Ian Shef
I don't have the book in front of me, but if I recall correctly:
The book tells you to avoid yield(). It has no testable semantics,
and
may be implemented as a NO-OP.
Instead, use sleep(...). However, don't use sleep(0), use sleep(1).
I am at work, my book is at home. Maybe someone with immediate access
to the book can comment?
A follow-up to my own follow-up...
In the book by Brian Goetz with Tim Peierls, Joshua Bloch, Joseph Bowbeer,
David Holmes and Doug Lea, Java Concurrency in Practice, 6th Printing,
March 2008
Footnote 5 on page 218 (Section 10.3.1 Starvation)
"The semantics of Thread.yield (and Thread.sleep(0)) are undefined [JLS
17.9]; the JVM is free to implement them as no-ops or treat them as
scheduling hints. In particular, they are not required to have the
semantics of sleep(0) on Unix systems – put the current thread at the end
of the run queue for that priority, yielding to other threads of the same
priority – though some JVM implementations yield in this way."
In the book by Joshua Bloch, Effective Java, Second Edition, 4th Printing,
September 2008
Page 287 (Item 72: Don't depend on the thread scheduler)
"Thread.yield has no testable semantics."
....
"In the first edition of this book, it was said that the only use most
programmers would have for Thread.yield was to artificially increase the
concurrency for testing. The idea was to shake out bugs by exploring a
larger fraction of the program's statespace. This technique was once quite
effective, but it was never guaranteed to work. It is within specification
for Thread.yield to do nothing at all, simply returning control to its
caller. Some modern VMs actually do this. Therefore, you should use
Thread.sleep(1) instead of Thread.yield for concurrency testing. Do not use
Thread.sleep(0), which can return immediately."
So JCP has part of the information, but EJ goes into more detail and is
what I was remembering. I have both books and I am trying to learn from
them, but I don't necessarily remember which nuggets of information are
from which book.