Re: wait vs. yield?
On 5/30/2010 2:25 PM, Marcin Rodzik wrote:
On May 29, 9:42 pm, Eric Sosman<esos...@ieee-dot-org.invalid> wrote:
Thread.sleep()
Thread.yield()
Both techniques are *vastly* inferior to wait().
So whay does yield() exist? Is there any case in which it can be
preferred?
I can't think of a reason to use yield(), unless you happen to
be writing Java for one specific platform and you know a lot about
how that platform schedules threads. That is, I cannot think of a
way to use yield() and get the same effect on multiple platforms.
On the surface, it *sounds* simple: yield() "causes the
currently executing thread object to temporarily pause and allow
other threads to execute." But how long is "temporarily," and
which "other threads" are eligible to execute? On many systems,
if thread T1 has higher priority than T2 and calls yield(), the
scheduler will take T1 off the CPU and put it right back on again,
since it's the highest-priority runnable thread. At best, you can
hope that all threads with priority equal to T1's will get a chance
to run before T1 gets the CPU again, but even that's not guaranteed.
Low-priority T2 is not likely to get any increase in CPU time because
of a yield() by high-priority T1.
Even if you create T1 and T2 with equal priority (from Java's
point of view), it may turn out that Java's thread priorities do not
map exactly to those of the underlying platform. Many systems, for
example, keep track of a thread's execution history and adjust a
low-level "scheduling priority" to try to improve overall system
throughput. The default scheduling classes in Solaris, for example,
try to raise the priorities of I/O-bound threads and lower those of
CPU-bound threads. Putting the I/O-bound thread first allows it to
start its next I/O sooner so it can be in progress while the CPU-
bound thread executes. In the face of this kind of dynamic priority
adjustment, it becomes difficult to predict whether T1 or T2 has the
higher "effective" priority.
In short, I can't think of a portable reason to use yield() --
maybe somebody smarter than I am knows of one, but I don't. As to
why it exists, I don't really know but I surmise the Java designers
decided to incorporate most of the POSIX Pthreads facilities, and
Pthreads has yield() analogs (with similar drawbacks). We should
consider ourselves lucky, I guess, that they decided to omit the
horrendous Pthreads cancellation mechanisms!
The newsgroup comp.programming.threads is a good place for thread
questions. Some of the people who wrote the Pthreads standards hang
out there, and may be able to tell you why Pthreads' equivalents of
yield() exist. Lots of those people know Java, too.
--
Eric Sosman
esosman@ieee-dot-org.invalid