The solution I made is the one proposed by pingw33n. Using the volatile
keyword.
class Controller extends Thread implements ConfigurationObserver{ private volatile int refreshMS;
Quote from Brian Goetz Volatility Management
Volatile variables share the visibility functions of a synchronized, but not one of the features of atomicity. This means that threads will automatically see the most current value for volatile variables.
This means that volatile
can be used instead of synchronized
in very few cases. But, fortunately, this is one of them, since int
is typed atomically (a thread cannot read its value, and the other modifies it).
Therefore, as Stephen S said, this does not eliminate the state of the race, it only makes it a truly rare case. In my case, if refresMS
read with the old value by the working thread, it doesn't matter much (if it's something that barely happens).
source share