Everywhere in the internet it is said that hashmap isn't thread-safe. Use alternatives.
But what exact issues could happen in concurrent use of hashmap? Could you provide concrete examples.
Everywhere in the internet it is said that hashmap isn't thread-safe. Use alternatives.
But what exact issues could happen in concurrent use of hashmap? Could you provide concrete examples.
Consider the following example where we provoke an error:
Map<Object, Object> test = new HashMap<>();
new Thread() {
@Override
public void run() {
for (;;)
test.put(Math.random(), Math.random());
}
}.start();
for (;;)
for (Entry<Object, Object> e : test.entrySet())
System.out.println(e);
There are two threads that access the map "test". One inserts and the other iterates over the map. You will get a ConcurrentModificationException immediately, because the first thread inserts while the second is in the middle of iterating over the previous map state.
Thread safe map implementations will snapshot the map state and ignore changes that occur afterwards.