Java: How to take a static snapshot of ConcurrentHashMap?

Java doc says that return values ​​of method () and entrySet () values ​​are supported by the map. Therefore, changes in the map are reflected in the set and vice versa. I do not want this to happen with my static copy. Essentially, I want a lot of parallel operations to be performed on my DS. But in some cases I want to repeat a static snapshot. I want to repeat the static snapshot as I assume that iterating over the static snapshot will be faster compared to the version that is being updated at the same time.

+4
source share
2 answers

Just make a copy, the new HashMap will be independent of the original.

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

However, remember that once a complete iteration will be performed on concurrentStructure, but only then there will be static snapshots. Thus, you will need the time equivalent to one full iteration.

+1
source

Just make a copy and it will not be changed.

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

All implementations of the collection have a copy constructor that copies all the data of the supplied collection to the newly created one, without being backed up by the original.

: entrySet(), - "" , . entrySet(), , .

Set<Entry<K,V>> entrySetCopy = new HashMap<>(map).entrySet();

, ONCE ( ) . , .

+7

All Articles