multithreading - Java Singleton Synchronization for multi-thread using HashMap -


i have following 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);     }    

i thought enough avoid concurrent access, got error :

hashmap.java checkconcurrentmod java.util.hashmap$abstractmapiterator java.util.concurrentmodificationexception unhandled exception in plugin method java.util.concurrentmodificationexception 

i have 10 threads using class, , throws error approximately 1 time every 100.000 call.

whats wrong singleton ?

the problem hashmaps not thread safe can read in linked docs.

you should try changing them concurrenthashmaps.

aside should change singleton implementation better handle multi threading. wikipedia page on double-checked locking provides lot of examples.

p.s.: instead of declaring variables hashmaps should declare them maps. way can change specific implementation without having refactor anything. called programming interfaces.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -