0

I have a class ConfigService. The field config in this class is designated as volatile. It is assumed that several threads will read config using getConfig(), and one thread will update using update() . Will reader threads see new values in config object if a new newConfig object is assigned in the config field?

public class ConfigService{
    private volatile Config config = new Config();

    public updateConfig(Config newConfig){
        config = newConfig;
    }

    public Config getConfig() {
        return config;
    }
}

public class Config{
    private Integer myInt;
    private String myString;

    public Integer getMyInt() {
        return myInt;
    }

    public String getMyString() {
        return myString;
    }

}
Violetta
  • 509
  • 4
  • 12
  • i found a nice explanation here - [Java volatile](http://tutorials.jenkov.com/java-concurrency/volatile.html), maybe it will help you out – LiavC Feb 15 '22 at 08:46
  • Does this answer your question? [What is the volatile keyword useful for?](https://stackoverflow.com/questions/106591/what-is-the-volatile-keyword-useful-for) – pringi Feb 15 '22 at 10:02

1 Answers1

0

As long as you do not update the Config after it is set on the ConfigService you should be alright.

Explanation. The code should be without a data race. A data race condition is caused where there is no happens-before edge between write and a read (or write). The volatile variable will ensure that a happens-before edge between the write and read of myInt/mystring exist.

If you would modify the Config object AFTER it is set on the ConfigService, then you could end up with data races.

If you want to have more detail, I can provide it.

pveentjer
  • 10,545
  • 3
  • 23
  • 40