Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get and Put to Map at same time in Java

I have one doubt. What will happen if I get from map at same time when I am putting to map some data?

What I mean is if map.get() and map.put() are called by two separate processes at the same time. Will get() wait until put() has been executed?

like image 238
hatellla Avatar asked Jun 29 '15 06:06

hatellla


People also ask

What is synchronization map in Java?

The synchronizedMap() method of java. util. Collections class is used to return a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map.

Can we compare two HashMaps in Java?

We can compare two HashMap by comparing Entry with the equals() method of the Map returns true if the maps have the same key-value pairs that mean the same Entry.

Are HashMaps resized automatically in Java?

As you again are likely aware, the HashMaps are resized dynamically during runtime, based on the number of entries in the map. By default, the HashMaps uses a load factor of 75%.


1 Answers

It depends on which Map implementation you are using.

For example, ConcurrentHashMap supports full concurrency, and get() will not wait for put() to get executed, and stated in the 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 (such as HashMap) don't support concurrency and shouldn't be used by multiple threads at the same time.

like image 82
Eran Avatar answered Sep 29 '22 06:09

Eran