我正在阅读有关单例模式的维基,我不确定我是否理解这一点:https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom正确部分.
所以要简单一点:为什么Bill Pugh的解决方案比上面的例子更好?
是因为VM在实际使用之前没有加载静态类或类似的东西,所以在转向getInstance()方法之前我们不创建对象?那个方法线程安全只是在初始化对象的程度吗?
我有一个缓存,我使用simeple HashMap实现.喜欢 -
HashMap<String,String> cache = new HashMap<String,String>();
Run Code Online (Sandbox Code Playgroud)
大多数时候使用此缓存来从中读取值.我有另一个方法重新加载缓存,在这个方法内部我基本上创建一个新的缓存,然后分配引用.据我所知,对象引用的赋值是Java中的Atomic.
public class myClass {
private HashMap<String,String> cache = null;
public void init() {
refreshCache();
}
// this method can be called occasionally to update the cache.
public void refreshCache() {
HashMap<String,String> newcache = new HashMap<String,String>();
// code to fill up the new cache
// and then finally
cache = newcache; //assign the old cache to the new one in Atomic way
}
}
Run Code Online (Sandbox Code Playgroud)
我理解如果我不将缓存声明为volatile,其他线程将无法看到更改,但对于我的用例将缓存中的更改传播到其他线程并且它们可以继续使用旧缓存并不是时间关键延长时间.
你看到任何线程问题吗?考虑到许多线程正在从缓存中读取,并且有时只重新加载缓存.
编辑 - 我的主要困惑是我不必在这里使用AtomicReference,因为赋值操作本身是原子的?
编辑 - 我理解为了使顺序正确,我应该将缓存标记为volatile.但是如果refreshCache方法被标记为synchronized,我不必将缓存设置为volatile,因为Synchronized块将负责排序和可见性?