小编jde*_*del的帖子

使用HashMap的多线程Java Singleton Synchronization

我有以下课程:

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);
    }   
Run Code Online (Sandbox Code Playgroud)

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

HashMap.java
checkConcurrentMod
java.util.HashMap$AbstractMapIterator
java.util.ConcurrentModificationException
Unhandled exception in plugin method
java.util.ConcurrentModificationException
Run Code Online (Sandbox Code Playgroud)

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

这个单身人士怎么了?

java singleton multithreading hashmap synchronized

6
推荐指数
1
解决办法
1407
查看次数

标签 统计

hashmap ×1

java ×1

multithreading ×1

singleton ×1

synchronized ×1