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;
}
}
Instances of this class is accessed from just 1 thread, except the timeout variable which can be altered from another class. In my case a JMX bean, which means one can alter the timeout during runtime from a management interface.
The doStuff() could be running 100's of times/second, while the setTimeout() could be run once a week - so the ordering between someone doing setTimeout() and someone doing doWork() is not important.
Is making timeout
volatile sufficient for such a case ? Will the memory model guarantee that setting this from one thread to be visible to the doStuff()
method ?
Another alternative that seems safe would simply be:
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 of these 2 approaches would be preferred ?