Joker
Joker

Reputation: 11154

Unable to add elements in concurrent HashMap - Why?

Wrote following test code for my understanding on Concurrent HashMap

My problem is code is not working as intended and I think it ends up into infinite loop where JVM is not terminating.

public class Test {
    public static void main(String[] args) {
        Map<Long, Long> map = new ConcurrentHashMap<>();
        map.put(0L, 0L);
        map.put((1L << 32) + 1, 0L); 
        for (long key : map.keySet()) {
            map.put(key, map.remove(key));
        }
    }
}

I am not sure why this is happening , can some one help me understand this behavior.

Upvotes: 0

Views: 93

Answers (1)

0xadecimal
0xadecimal

Reputation: 726

I'm not sure exactly what you intended the code to do, however you are correct in thinking your code is stuck in an infinite loop. The line below is what is creating the infinite loop:

map.put(key, map.remove(key)); 

The concurrent hash map documentation for the remove method states:

... returns the previous value associated with key, or null if there was no mapping for key

Thus your code is simply iterating over the map, updating each entry with it's current value. If the map only had 1 entry it would break out of the for loop.

Upvotes: 1

Related Questions