如何获取ConcurrentHashMap的静态快照

如何获取ConcurrentHashMap的静态快照

本文介绍了Java:如何获取ConcurrentHashMap的静态快照?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java文档表示,映射支持方法values()和entrySet()的返回值.因此,对地图的更改会反映在集合中,反之亦然.我不希望这种情况发生在我的静态副本上.本质上,我希望在DS上完成许多并发操作.但是对于某些情况,我想遍历其静态快照.我想遍历静态快照,因为我假设与同时更新的版本相比,遍历静态快照会更快.

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.

推荐答案

简单地制作一份副本,新的HashMap将与原始副本无关.

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.

这篇关于Java:如何获取ConcurrentHashMap的静态快照?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:22