This class extends Thread and once it is created, the thread is started. This is the code:
class Controller extends Thread implements ConfigurationObserver{
private int refreshMS;
//...
@Override
public void notifyConfiguration(ConfigurationModel config) {
refreshMS = config.getRefreshMs();
}
@Override
public void run() {
//...
while (true) {
try {
Thread.sleep(refreshMS);
} catch (InterruptedException ex) {
//...
}
}
}
}
It follows the Observer Pattern. This class will subscribe itself to the ConfigurationController which will notify him every time there is a change in any of the configuration parameters, through notifyConfiguration(...)method.
What makes me a little insecure about this, is the attribute refresMS. Configuration is changed through the GUI (Thread #1) and affects the attribute of Controller class (Thread #2) which is read from the running thread of that class (Thread #3).
Q1: Could this become a race condition?
Q2: If so, what is it the best way to solve this problem?
The solution I did is the one pingw33n suggested. Using the keyword
volatile.Quote from Brian Goetz’s Managing Volatility
Which means that
volatilecould be used instead ofsynchronizedin very few cases. But luckly this is one of them, sinceintis writed atomicly (no thread can read its value while other one is modifying it).Therefore, as Stephen C said, this does not eliminates the race condition, it only makes it really rare to happen. In my case, if the
refresMSis readed with an old value by the running thread is not a big deal (if it is something that barely happens).