I have a Spring bean class that look similar to the following:
@Component
public class Foo{
private Config conf;
@PostConstruct
public void init(){
conf = ConfigFileLoader.loadConfigFromFile();
}
public Config getConfig(){
return conf;
}
public void updateConfig(){
conf = ConfigFileLoader.loadConfigFromFile();
}
}
ConfigFileLoader.loadConfigFromFile() reads configuration from file and returns a new Config object.
There are two types of threads:
- Updater thread:
- there is only one
- it calls updateConfig periodically (when it detects changes on the configuration file)
- Reader thread:
- multiple threads are calling getConfig using the Config object for execution.
- does not care if it receives a stale Config object instance for current execution as long as eventually reader threads start getting an up to date Config object.
My question is this, should i mark the private conf field as volatile or maybe add some kind of synchronisation for conf field?
My fear is the following scenario: the Updater thread updates the conf reference but the change is never made visible to the reader threads.
Any help or explanation will be appreciated.
volatilework means that when the reference to your variable changes, it will take effect for every thread. So yes, this change will be visible to the reader threads whether you declare it as volatile. - Héctor