JavaQuest
JavaQuest

Reputation: 713

What happens when two threads try to modify/ access the same key in Concurrent HashMap?

I read about hashMap and how it is different from hashtable. Like in hashtable the complete object gets locked while in case of concurrent hashmap only a part of it is locked. My question is what happens when two threads try to access the same value correspoding to a key at the samme time.

Lets say

 Map mp = new ConcurrentHashMap(); 
 mp.put(1, "Hello");

Thread 1: trying to read mp.get(1).

Thread 2: trying to write/modify into it mp.put(1, "Hi").

so What value does thread 1 gets to read?

Edit: I meant ConcurrentHashMap.

Upvotes: 3

Views: 2223

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533530

What value does thread 1 gets to read?

It will read two possible values, either

  • it gets null as the value hasn't been set yet.
  • it get the value Thread 2 set.

This might not sound like a great deal but you should note that with HashMap it is possible to go into an infinite loop and never return, which is bad.

Where ConcurrentHashMap is really useful is in operations like putIfAbsent For passing work between threads, a Queue is much better choice.

ConcurrentMap<Integer, BlockingQueue<String>> map = ...

Thread 1

String value = map.putIfAbsent(1, k -> new BlockingQueue<>()).take();

Thread 2

map.putIfAbsent(1, k -> new BlockingQueue<>()).offer("Hi");

In this case, Thread 1 will block until Thread 2 has added a value. Note: this value is only available once.

Upvotes: 5

Related Questions