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

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?
Comments:

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.

Posted by Bharath R on June 30, 2006 at 06:10 AM IST #

Bharat: Precisely! The update to the instance field could never be seen at all.

Posted by A. Sundararajan on June 30, 2006 at 07:03 AM IST #

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).

Posted by Marcus Sundman on June 30, 2006 at 11:52 AM IST #

Post a Comment:
Comments are closed for this entry.
About

sundararajan

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today
Bookmarks
Links

No bookmarks in folder

Blogroll

No bookmarks in folder

News

No bookmarks in folder