Skip to content

Instantly share code, notes, and snippets.

@IgorBerman
Created August 12, 2014 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IgorBerman/7736357ded9109527569 to your computer and use it in GitHub Desktop.
Save IgorBerman/7736357ded9109527569 to your computer and use it in GitHub Desktop.
double locking on atomic reference(is it correct?)
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
public class Test {
private AtomicReference<Config> configHolder = new AtomicReference<Config>();
private static final class Config {
private final Map<String, Double> factorsMap;
Config(Map<String, Double> factorsMap) {
this.factorsMap = factorsMap;
}
}
private Config get() {
if (configHolder.get() == null) {
synchronized (configHolder) {
if (configHolder.get() == null) {
//suppose long initialization here for factorsMap
Map<String, Double> factorsMap = new HashMap<String, Double>();
Config config = new Config(factorsMap);
configHolder.set(config);
}
}
}
return configHolder.get();
}
public Double getFactor(String key) {
return get().factorsMap.get(key);
}
}
@IgorBerman
Copy link
Author

enough to use volatile(didn't remember if volatile supports references) instead of AtomicReference. The last has meaning of continuous read-write. Here we have 1 time initialization

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment