集合锁问题

zdd2389 2014-08-21 09:10:16
看到别人的代码中有这样一个类,如下:
public abstract class BaseMemoryCache implements MemoryCache {

/** Stores not strong references to objects */
private final Map<String, Reference<Bitmap>> softMap = Collections.synchronizedMap(new HashMap<String, Reference<Bitmap>>());

@Override
public Bitmap get(String key) {
Bitmap result = null;
Reference<Bitmap> reference = softMap.get(key);
if (reference != null) {
result = reference.get();
}
return result;
}

@Override
public boolean put(String key, Bitmap value) {
softMap.put(key, createReference(value));
return true;
}

@Override
public Bitmap remove(String key) {
Reference<Bitmap> bmpRef = softMap.remove(key);
return bmpRef == null ? null : bmpRef.get();
}

@Override
public Collection<String> keys() {
synchronized (softMap) { //这边为什么还要加一个同步锁???
return new HashSet<String>(softMap.keySet());
}
}

@Override
public void clear() {
softMap.clear();
}

/** Creates {@linkplain Reference not strong} reference of value */
protected abstract Reference<Bitmap> createReference(Bitmap value);
}

变量softMap已经是Collections.synchronizedMap,为什么keys方法里面还要加上一句synchronized(softMap)?
...全文
108 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
菜鸟大明 2014-08-21
  • 打赏
  • 举报
回复
楼上的这篇文章说的很清楚。
skgary 2014-08-21
  • 打赏
  • 举报
回复
http://blog.sina.com.cn/s/blog_5157093c0100hm3y.html 这个文章写的比较详细,楼主可以参考一下。
skgary 2014-08-21
  • 打赏
  • 举报
回复
keys是重新new一个hashSet,然后将所有的key放到这个hashSet里。 主要担心是在复制的过程中,keys会有所改变。 synchronizedMap本身是同步的,但这只限于他自己的读写方法是线程安全的。 但不代表在复制key的过程中也是 锁的。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧