-2

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.

voipp
  • 1,243
  • 3
  • 18
  • 31
  • Your program could throw an unexpected exception, or the hash map could give wrong results. It's not defined behaviour. Just don't. – Thomas Mar 07 '21 at 15:04
  • You should have a specific example in mind for a question like this. Generally folks here won't answer broad questions. Try to narrow the question down and provide a code example. – markspace Mar 07 '21 at 15:04
  • Does this answer your question? [What is a race condition?](https://stackoverflow.com/questions/34510/what-is-a-race-condition) – Tom Mar 07 '21 at 15:23
  • @Tom race condition is too broad answer. I need concrete examples. Like below – voipp Mar 07 '21 at 15:25

1 Answers1

0

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.

aeberhart
  • 744
  • 1
  • 4
  • 15