Can Java be unstable and ensure visibility?

public class Stuff {
public class Stuff {
  private final Timer timer = new Timer(true);
  public static final int DEFAULT_TIMEOUT = 1500;
  private volatile int timeout = DEFAULT_TIMEOUT;


  public void doStuff(OtherStuff) {
     ...
     timer.schedule(timeout,...);
  }

  public void setTimeout(int timeout) {
     this.timeout = timeout;
  }

  public int getTimeout() {
    return timeout;
  }

}

Except for the timeout variable that can be changed from another class, instances of this class are accessed from only one thread In my example, it is a JMX bean, which means that the timeout can be changed from the management interface at run time

Dostuff() can run 100 times per second, while settimeout() can run once a week – so the order between the person executing settimeout() and the person executing dowork() is not important

Is the timeout sufficient for this situation? Does the memory model guarantee that setting a thread to the dostuff () method is visible?

Another alternative that seems safe is:

public class Stuff {
  private final Timer timer = new Timer(true);
  public static final int DEFAULT_TIMEOUT = 1500;
  private int timeout = DEFAULT_TIMEOUT;
  public void doStuff(OtherStuff) {
     ...
     timer.schedule(getTimeout(),...);
  }

  public void synchronized setTimeout(int timeout) {
     this.timeout = timeout;
  }
   public int synchronized getTimeout() {
    return timeout;
  }
}

Which two methods are more popular?

Solution

From the perspective of visibility, both methods are equivalent Any reading of volatile after writing to the same volatile variable is guaranteed to see the write

Therefore, if a thread writes timeout = newvalue;, Then call timer.. Any other thread of the schedule (timeout) will be guaranteed to see the new value

This guarantee is in JLS 17.4 Specified in 5:

I will simply use volatile as the guarantee it provides. It clearly shows your intention

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>