java 使用 synchronizedSet 来同步两个线程之间的访问

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7857702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:43:18  来源:igfitidea点击:

Using a synchronizedSet to synchronize access between two threads

javamultithreadingsynchronizationthread-safetyset

提问by jasonline

I'm not able to synchronize two threads using a set:

我无法使用一组同步两个线程:

private Set<String> set;
...
set = Collections.synchronizedSet(new HashSet<String>());

and passing it to two threads. One accessing:

并将其传递给两个线程。一访问:

synchronized (set) {
    // [1]
    if (set.contains(str)) {
    ...
    } else {
        // [3]
    }
}

and another updating:

和另一个更新:

synchronized (set) {
    set.add(str);   // [2]
...
}

What happens is that [1], [2], [3] happens in sequence. During [1], it is correct that the set doesn't have yet the item I'm looking for. But then [2] updates it by adding the item. And during [3], I now see the item. How do I fix this? I also have a ConcurrentHashMap being shared by the same threads but it works perfectly fine. What is the set's equivalent to ConcurrentHashMAp?

发生的事情是 [1]、[2]、[3] 依次发生。在 [1] 期间,该套装还没有我要找的物品是正确的。但随后 [2] 通过添加项目来更新它。在 [3] 期间,我现在看到了该项目。我该如何解决?我也有一个 ConcurrentHashMap 由相同的线程共享,但它工作得很好。该集合与 ConcurrentHashMAp 的等价物是什么?

UPDATE: The code is too long. Anyway, my updated question is - What is the set's equivalent to ConcurrentHAshMap?

更新:代码太长。无论如何,我更新的问题是 - 与 ConcurrentHAshMap 等效的集合是什么?

回答by Sean Owen

You are synchronizing access correctly. Actually, wrapping it in synchronizedSet()is not having any additional effect here. There is no ConcurrentHashSetthough you can kind of get the same thing from Collections.newSetFromMap()and ConcurrentHashMap. But this isn't the problem.

您正在正确同步访问。实际上,将它包裹起来synchronizedSet()并没有任何额外的效果。没有ConcurrentHashSet,虽然你可以种得到同样的事情Collections.newSetFromMap()ConcurrentHashMap。但这不是问题。

The problem is somewhere else in your code. For example: are you sure you're synchronizing on the same set? are your keys implementing hashCode()and equals()correctly? have you made them mutable (bad idea) and something is changing the keys?

问题出在您的代码中的其他地方。例如:您确定要在同一台设备上同步吗?是你的钥匙实施hashCode()equals()正确?你有没有让它们可变(坏主意)并且某些东西正在改变密钥?