I have the following code that gets initialized as a static variable in a class:
public class MyXlet extends Xlet {
boolean connected = false;
...
void connect() {
// some code goes here, starts a new thread
MyXlet.connected = true;
}
void disconnect() {
// some code goes here, the new thread is designed to terminate once connected is false;
MyXlet.connected = false;
}
}
Let’s say I have already run the connect method, which spawns a new thread. The disconnect() method sets “connected” to “false”. Is it guaranteed that the thread that was spawned from the connect() method will see that “connected” is no longer equal to “true”? Or will I have to use the volatile keyword on “connected” for this? It is worthy to note that I am using Java 1.4.2.
Only if the thread that was spawned from the
connect()method is the one that setsconnectedtofalse!The spawned thread will be able to see that
connectedis true after it is started, because starting a thread is a happens-before action, and source code also establishes a happens-before ordering within a thread.But, if the parent thread clears the
connectedflag after callingstart()on the spawned thread, the spawned thread is not guaranteed to see the change unless you declare the flag asvolatile.The main difference between 1.4 and 1.5 behavior is that writing to a
volatilevariable will also flush writes to non-volatile variables from Java 5 onward. (Reading a volatile variable also clears any cached non-volatile variable values.) Since it appears that you only have one variable involved, this change shouldn’t affect you.