« November 2009
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
XML

Blog::Navigation

GetJava Download Button
Get the Source
Personal Blog

Blog::Referers

Today's Page Hits: 469

Powered by Roller Weblogger.
« From Emacs/ELisp to... | Main | Not much to see in... »
20060630 Friday June 30, 2006

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?



( Jun 30 2006, 09:32:51 AM IST ) Permalink Comments [3] del.icio.us | furl | simpy | slashdot | technorati | digg

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 01:10 PM IST #

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

Posted by A. Sundararajan on June 30, 2006 at 02:03 PM 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 06:52 PM IST #

Post a Comment:

Comments are closed for this entry.
Copyright (C) 2005, A. Sundararajan's Weblog