Re: JavaMemoryModel: Guaranteed semantics for Thread.yield()

From: Joseph Bowbeer (jozart@csi.com)
Date: Wed Jan 02 2002 - 01:47:25 EST


My $0.02 on yield:

I've only used yield to do two things:

1. In a background thread in a GUI app in an attempt to make the UI more
responsive. The background thread yields periodically in order to give the
event-dispatch thread as much time as it needs (but no more). Since the
scheduling of the event-thread is outside the control of the app,
Thread.yield() is about the only option, I think. Perhaps this is an issue
that should be addressed in the GUI API.

2. As a temporary tweak to the JVM's thread scheduler until I get around to
implementing my own scheduler.

I think it's fine to keep Thread.yield() vague. I would define yield as a
"suggestion" or "hint" to the JVM. On return from yield, the JVM will have
made its "best effort" to give some other thread a chance to run, pausing
the current thread if needed. Such a definition wouldn't change the fact
that Thread.yield() doesn't have to "do" anything. (Is this any different
to how yield is defined now?)

----- Original Message -----
From: "Bill Pugh" <pugh@cs.umd.edu>
To: <javamemorymodel@cs.umd.edu>
Sent: Monday, December 31, 2001 7:20 AM
Subject: JavaMemoryModel: Guaranteed semantics for Thread.yield()

In finishing up our writeup on fairness, I think we need to guarantee
some semantics for Thread.yield() and Thread.sleep().

Specifically, either operation should have the semantics that with
some finite probability, some other eligible thread of equal or
higher priority is allowed to execute at least one instruction.

On systems with full preemptive multithreading, this is a no-op,
since it is always the case that with some finite probability some
other eligible thread will be allowed to execute. However, on systems
that don't have preemptive multithreading, or that only allow context
switches at compiler defined points, this guarantee will have
semantics.

This guarantee will ensure that both of the following two examples
terminate, while without the guarantee they can both fail to
terminate.

Example 1:
Initially, volatile x = 0

Thread 1:
while (x == 0) {
Thread.yield();
}

Thread 2:
x = 1

Example 2:
Initially, x = 0 (x is non-volatile in this example).

Thread 1:
int r1;
do {
Thread.yield();
synchronized(this) {
  r1 = x;
           }
     } while (r1 == 0);

Thread 2:
synchronized(this) {
   x = 1
   }

-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:36 EDT