Get and Put to Map at the same time in Java

I have one doubt. What happens if I receive from the card at the same time that I place the card to display some data?

I mean, if you map.get()and map.put()caused the two separate processes at the same time. Will it get()wait until put()it is completed?

+4
source share
3 answers

It depends on which map implementation you use.

For example, it ConcurrentHashMapsupports full concurrency, but get()will not wait for execution put()and will be specified in Javadoc:

 * <p> Retrieval operations (including <tt>get</tt>) generally do not
 * block, so may overlap with update operations (including
 * <tt>put</tt> and <tt>remove</tt>). Retrievals reflect the results
 * of the most recently <em>completed</em> update operations holding
 * upon their onset.

Other implementations (e.g. HashMap) do not support concurrency and should not be used by multiple threads at the same time.

+5

Map - , .

, , HashMap TreeMap . , put ing get ing undefined - , , bust, , d ConcurrentModificationException, - .

Map , ConcurrentMap (, a ConcurrentHashMap), - (.. get put, 'd , put , ) Map (, Collections#synchronizedMap(Map).

+1

It may raise a ConcurrentModificationException - not sure about that. It is always better to use synchronizedMap. This is usually done by synchronizing on some object, which naturally encapsulates the map. If such an object does not exist, the map must be “wrapped” using the Collections.synchronizedMap method. This is best done at creation time to prevent accidental unsynchronized access to the map:

Map map = Collections.synchronizedMap(new HashMap(...));
+1
source

All Articles