Sundararajan's Weblog

  • Java
    June 29, 2006

Is this MT-safe? I think not...

Guest Author
I came across this article recently: A Safe Way to Stop a Java Thread. The author suggests an alternative for the deprecated Thread.stop()
method. The code looks like

public class MyThread extends Thread {
private boolean threadDone = false;
public void done() {
threadDone = true;
public void run() {
while (!threadDone) {
// work here
// modify common data

MyThread.done() is supposed to be called by another thread that wants to stop a thread (that is running MyThread.run()). But, there is a problem here: threadDone variable is read by one thread and written by another thread. To ensure prompt communication of the stop-request, the threadDone variable must be volatile (or access to the threadDone variable must be synchronized):
volatile private boolean threadDone = false;

Please refer to this as well: Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?

Join the discussion

Comments ( 3 )
  • Bharath R Friday, June 30, 2006
    There is, in fact, a possibility that MyThread might never \*ever\* see the new value of threadDone when running on a multiprocessor. Even on a uniprocessor , the JMM doesn't provide any guarantee.
  • A. Sundararajan Friday, June 30, 2006
    Bharat: Precisely! The update to the instance field could never be seen at all.
  • Marcus Sundman Friday, June 30, 2006
    It depends on what you mean by "MT-safe". Although the thread reading threadDone might never see its updated value, reading a boolean is still atomic and thus is not thread-unsafe (as opposed to reading a long, for example). The code just doesn't behave like the programmer might have expected, but the same goes for a lot of things (e.g., writing to System.out or a network socket might delay its output indefinitely if you don't flush() it).
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.