简体   繁体   English

来自地图的同步集还是来自同步地图的集?

[英]Synchronized set from map or set from synchronized map?

I need a concurrent weak hash set without using Guava collections. 我需要不使用Guava集合的并发弱哈希集。 Which one is correct? 哪一个是正确的? Any side effects? 有副作用吗?

private Set<Session> subscribers1 = Collections.newSetFromMap(
        Collections.synchronizedMap(new WeakHashMap<Session, Boolean>())
);
private Set<Session> subscribers2 = Collections.synchronizedSet(
        Collections.newSetFromMap(new WeakHashMap<Session, Boolean>())
);

If you look at the implementations, it's almost the same. 如果看一下实现,那几乎是一样的。

Collections.newSetFromMap creates a new SetFromMap extends AbstracSet instance. Collections.newSetFromMap创建一个新的SetFromMap extends AbstracSet实例。 The SetFromMap class is basically a wrapper around a map object. SetFromMap类基本上是地图对象的包装器。 But it does inherit the addAll method from the AbstracSet . 但是它确实从AbstracSet继承了addAll方法。 This means that in the first option: 这意味着在第一个选项中:

private Set<Session> subscribers1 = Collections.newSetFromMap(
        Collections.synchronizedMap(new WeakHashMap<Session, Boolean>())
);

not all operations will be synchronized (namely the addAll method - though it uses the synchronized add method under the hood). 并非所有操作都将被同步(即addAll方法-尽管它在addAll使用了同步的add方法)。 Due to this fact I'd recommend choosing the second option: 由于这个事实,我建议选择第二个选项:

private Set<Session> subscribers2 = Collections.synchronizedSet(
        Collections.newSetFromMap(new WeakHashMap<Session, Boolean>())
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM