开发者

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

开发者 https://www.devze.com 2023-04-04 20:05 出处:网络
I have the following code that gets initialized as a static variable in a class: public class MyXlet extends Xlet {

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 开发者_JAVA技巧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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号