gpt4 book ai didi

java - 同步 BiMap 逆 View 的同步

转载 作者:太空宇宙 更新时间:2023-11-04 11:28:47 25 4
gpt4 key购买 nike

Maps.synchronizedBiMap() 方法指出

it is imperative that the user manually synchronize on the returned map when accessing any of its collection views.

这是否包括 BiMap 的 inverse() View ?例如,如果变量按以下示例初始化,从其他线程调用 inverse.put() 是否会出现问题(例如,在 mapinverse 上的 get() 调用中看不到更改,即使 put happened-before get 也是如此)?

BiMap<Object, Object> map = Maps.synchronizedBiMap(HashBiMap.create());
BiMap<Object, Object> inverse = map.inverse();

如果这确实是一个问题,是否有标准/推荐的方法来解决这个问题?

//编辑

从实现来看,SynchronizedBiMapinverse() 似乎也是一个 SynchronizedBiMap,共享相同的 mutex。这是否意味着所描述的问题不存在?非常感谢 Guava Collections 专家的确认;)

最佳答案

不,在这种情况下,您不必在反向 map 上同步。您只引用了文档的一个片段,我还将在示例代码中将原始 keySet()inverse() 切换:

Returns a synchronized (thread-safe) bimap backed by the specified bimap. In order to guarantee serial access, it is critical that all access to the backing bimap is accomplished through the returned bimap.

It is imperative that the user manually synchronize on the returned map when accessing any of its collection views:

BiMap<Long, String> map = Maps.synchronizedBiMap(
HashBiMap.<Long, String>create());
//...
BiMap<String, Long> inverse = map.inverse(); // Needn't be in synchronized block
Set<String> set = inverse.keySet(); // Needn't be in synchronized block
//...
synchronized (map) { // Synchronizing on map, not set!
Iterator<String> it = set.iterator(); // Must be in synchronized block
while (it.hasNext()) {
foo(it.next());
}
}

Failure to follow this advice may result in non-deterministic behavior.

因此,当您希望在其 View 迭代期间(包括迭代逆 View )期间获得确定性行为时,您必须在实例上进行同步。

如果是 .inverse(),正如您提到的,it creates new synchronized bimap using same mutex object ,因此它可以在 getcontains 等方法上正确同步。

关于java - 同步 BiMap 逆 View 的同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44050911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com