Created
August 12, 2014 12:22
-
-
Save IgorBerman/7736357ded9109527569 to your computer and use it in GitHub Desktop.
double locking on atomic reference(is it correct?)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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