Synchronization in a HashMap cache(HashMap 缓存中的同步)
问题描述
我有一个网络应用程序,人们在其中请求资源.为了提高效率,这些资源使用同步的哈希映射进行缓存.这里的问题是,当两个不同的请求同时针对同一个未缓存的资源时:检索资源的操作会占用大量内存,所以我想避免为同一个资源多次调用它.
I've got a web application where people ask for resources. This resources are cached using a synchronized hash map for efficiency. The problem here is when two different requests come for the same uncached resource at the same time: the operation retrieving the resources takes up a lot of memory, so I want to avoid calling it more than once for the same resource.
谁能告诉我以下代码段是否存在任何潜在问题?提前致谢.
Can somebody please tell me if there is any potential problem with the following snippet? Thanks in advance.
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);
}
}
}
...
}
推荐答案
一个可能的问题是您通过在 synchronized
块中执行 veryCostlyOperation()
来创建不必要的争用,因此许多线程无法同时检索它们的(独立)资源.这可以通过使用 Future
作为地图的值来解决:
One possible problem is that you create unnecessary contention by executing veryCostlyOperation()
inside a synchronized
block, so that many threads cannot retrieve their (independent) resources at the same time. This can be solved by using Future<Resource>
as values of the map:
Map<String, Future<Resource>> map = new ConcurrentHashMap<String, Future<Resource>>();
...
Future<Resource> r = map.get(name);
if (r == null) {
FutureTask task = null;
synchronized (lock) {
r = map.get(name);
if (r == null) {
task = new FutureTask(new Callable<Resource>() {
public Resource call() {
return veryCostlyOperation(name);
}
});
r = task;
map.put(name, r);
}
}
if (task != null) task.run(); // Retrieve the resource
}
return r.get(); // Wait while other thread is retrieving the resource if necessary
这篇关于HashMap 缓存中的同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:HashMap 缓存中的同步
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01