Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Unfortunately, the stop() method incorrectly uses the Thread.getState() method to check whether the thread is blocked and has not terminated before delivering the notification. Using the Thread.getState() method for synchronization control, such as checking whether a thread is blocked on a wait, is inappropriate. Java Virtual Machines (JVMs) are permitted to implement blocking using spin-waiting; consequently, a blocked thread may never enter thread can be blocked without entering the WAITING or TIMED_WAITING state [Goetz 2006]. Because the thread may never enter the WAITING state, the stop() method might fail to terminate the thread.

If doSomething() and stop() are called from different threads. It is possible for , the stop() to  method could fail to see the initialized thread even if though doSomething() was called earlier, unless there is a happens-before relationship between the two calls. If the two methods are invoked by the same thread, they automatically have a happens-before relationship , so they don't have and consequently cannot encounter this problem.

Compliant Solution

...

Code Block
bgColor#ccccff
public class Waiter {
  // ...
  private Thread thread;
  private volatile boolean flag;
  private final Object lock = new Object();

  public boolean stop() {
    if (thread != null) {
      flagsynchronized = true;
(lock) {
       synchronized (lock) { flag = true;
        lock.notifyAll();
      }
      return true;
    }
    return false;
  }
}

...