简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM