Two threads accessing the same hashmap, one thread continuously starts the other runs after 2 minutes and clears this hashmap, how to handle this in java

The first thread is a JMS subscriber who listens to the topic. As soon as he receives the message, he adds / updates / deletes entries in the hash map. Another thread starts every 2 minutes using TimerClass and reads the contents of the same hash of the file and saves it in the file and clears the hash map. Please indicate which type of hashmap-concurrent or synchronized should be used? is there any other way to achieve this?

+4
source share
4 answers

. HashMap .

Collections.SynchronizedMap Hashtable

+2

, - , .

" " , , , , , . , , .

+2

, , HashMap . :

synchronized(mapLock)
{
  map.put(...)
}

:

Map oldMap; 
synchronized(mapLock)
{
  oldMap = map;
  map = new HashMap<...>();
}
store(oldMap);

, .

ConcurrentHashMap . , JMS.

+1

? , 2 , 1, , , 2. .

storemap(){
 mapcopy=thread1.map;
 thread1.map=new Hashmap<Object>();
 store(mapcopy);
}
0

All Articles