gpt4 book ai didi

使用 HashMap 实现多线程的 Java 单例同步

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:28:33 24 4
gpt4 key购买 nike

我有以下类(class):

public class AggregationController {


private HashMap<String, TreeMap<Integer, String>> messages;
private HashMap<String, Integer> counters;
Boolean buildAggregateReply;
private boolean isAggregationStarted;

private static HashMap<String, AggregationController> instances = new HashMap<String, AggregationController>();

private AggregationController() throws MbException{
messages = new HashMap<String, TreeMap<Integer,String>>();
counters = new HashMap<String, Integer>();
buildAggregateReply = true;
isAggregationStarted = false;
}

public static synchronized AggregationController getInstance(String id) throws MbException{
if(instances.get(id) == null)
instances.put(id, new AggregationController());
return instances.get(id);
}

我认为这足以避免并发访问,但我得到了这个错误:

HashMap.java
checkConcurrentMod
java.util.HashMap$AbstractMapIterator
java.util.ConcurrentModificationException
Unhandled exception in plugin method
java.util.ConcurrentModificationException

我有 10 个线程使用这个类,它大约每 100.000 次调用抛出一次这个错误。

这个单例有什么问题?

最佳答案

问题很简单,HashMaps不是线程安全的,您可以在链接文档中阅读。

您应该尝试将它们更改为 ConcurrentHashMaps .

除此之外,您还应该更改单例实现以更好地处理多线程。 Double-checked locking 上的维基百科页面提供了很多很好的例子。

p.s.:与其将变量声明为 HashMap,不如将它们声明为 Maps。这样你就可以很容易地改变具体的实现,而不必重构任何东西。这叫做 Programming to interfaces .

关于使用 HashMap 实现多线程的 Java 单例同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31286042/

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