JavaMemoryModel: Problem with Thread.sleep

From: Bill Pugh (
Date: Sat Oct 23 1999 - 14:01:21 EDT

I've been working out some details and such of the memory model I proposed.
A bunch of email will be flying over the next few days.

I've encountered a serious problem with the way sleep is used. In a lot of
code, including code Sun distributed, you have code that looks like this:

Thread 1: // command handling thread

if (command.equals("quit") {
        terminateProgram = true;

Thread 2: // animation thread

while (!terminateProgram) {
        try { Thread.sleep(100); }
        catch (Exception e) {}
        update state

The basic problem is that it isn't clear that sleep should require a memory
barrier. Under the new scheme, "global memory barriers" don't even exist.
But unless we require a global memory barrier, there isn't any reason why
thread 2 should ever see the change to the variable terminateProgram.

How do people feel about this style? Is it bad enough that we can break
code written this

One way to fix the problem is to declare terminateProgram as volatile.
Another possibility is to use interrupts.

Basically, we could say that whenever thread T1 interrupts T2, that it is
treated as a release by T1 on the interrupt, when is acquired by T2 when it
detects the interrupt (e.g., by throwing an InterruptedException).



JavaMemoryModel mailing list -

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