简体   繁体   中英

Is the “volatile” keyword word needed in this instance? (Java)

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.

Is it guaranteed that the thread that was spawned from the connect() method will see that "connected" is no longer equal to "true"?

Only if the thread that was spawned from the connect() method is the one that sets connected to false !

The spawned thread will be able to see that connected is 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 connected flag after calling start() on the spawned thread, the spawned thread is not guaranteed to see the change unless you declare the flag as volatile .

The main difference between 1.4 and 1.5 behavior is that writing to a volatile variable 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.

Yes you should use volatile. This will ensure that when the field's value is updated all threads that check the field will have the updated value. Otherwise you are not ensured that different threads will get the updated value.

Well, even if you don't add the volatile keyword, other threads will be able to read the connected variable. By adding volatile, amongst other things, you make access to the variable synchronous.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM