我正在阅读这篇关于"双重检查锁定"的文章,并且在文章的主题之外我想知道为什么在文章的某些方面作者使用下一个成语:
清单7.尝试解决乱序写入问题
Run Code Online (Sandbox Code Playgroud)public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { //1 Singleton inst = instance; //2 if (inst == null) { synchronized(Singleton.class) { //3 inst = new Singleton(); //4 } instance = inst; //5 } } } return instance; }
我的问题是:有没有理由用同一个锁同步两次代码?有这个任何目的吗?
提前谢谢了.
我有一个人们要求资源的网络应用程序.为了提高效率,使用同步哈希映射缓存此资源.这里的问题是当同时为同一个未缓存的资源发出两个不同的请求时:检索资源的操作会占用大量内存,所以我想避免为同一个资源多次调用它.
有人可以告诉我,以下代码段是否存在任何潜在问题?提前致谢.
private Map<String, Resource> resources = Collections.synchronizedMap(new HashMap<String, Resource>());
public void request(String name) {
Resource resource = resources.get(name);
if (resource == null) {
synchronized(this) {
if (resources.get(name) == null) {
resource = veryCostlyOperation(name); // This should only be invoked once per resource...
resources.put(resource);
} else {
resource = resources.get(name);
}
}
}
...
}
Run Code Online (Sandbox Code Playgroud) java multithreading synchronization caching double-checked-locking