Search code examples
javajava.util.concurrentconcurrenthashmap

Java: How to take static snapshot of ConcurrentHashMap?


Java doc says that return values of method values() and entrySet() are backed by the map. So changes to the map are reflected in the set and vice versa. I don't want this to happen to my static copy. Essentially, I want lots of concurrent operations to be done on my DS. But for some cases I want to iterate over its static snapshot. I want to iterate over static snapshot, as I am assuming iterating over static snapshot will be faster as compared to a version which is being updated concurrently.


Solution

  • Simply make a copy, new HashMap would be independent of the original one.

    Set<K> keySetCopy = new HashSet<>(map.keySet());
    List<V> valuesCopy = new ArrayList<>(map.values());
    

    However mind that this will take a full iteration over the concurrentStructure, once but will only then be static snapshots. So you will need time equivalent to one full iteration.