Here are a few lines of code which I wrote to test hashmap’s performance in a multi-threading environment. I know that hashmap may cause deadlock with java8, but I am using java 11. It does not throw any exception, and never stop. Can someone help me to understand why? Thank you.
Response is a very simple entity class.
Advertisement
Answer
Java 11 implementation has not introduced thread-safe implementation of java.util.HashMap
.
In the JDK documentation, it is clearly stated that access to Hashmap
is NOT synchronized, so the behavior in a multithreaded application is unpredictable, and deadlock situation is indeed a possible side effect.
In addition, it is also said that if you want to have synchronized access, you MUST provide synchronization policy by using static method Collections.synchronizedMap
, this is the piece of code to realize that:
Map m = Collections.synchronizedMap(new HashMap(...));
Moreover, bear in mind that also the iterator provided implicitly or explicitly over the keyset or valueset is “fail-fast”, which means that it throws immediately a ConcurrentModificationException
when iterating through them and the map gets modified without using specific add
or remove
methods of the iterator itself.
If you are looking for better performances and, in particular, if you want to avoid any race condition, you can alternatively use java.util.concurrent.ConcurrentHashMap
, which guarantees not to throw any ConcurrentModificationException
.
In this case as well you can simply wrap your map with an instance of the concurrent one, so given K
and V
the types of the key and value:
Map<K,V> m = new ConcurrentHashMap<>(myHashMap);