克隆 ConcurrentHashMap

Cloning ConcurrentHashMap

为什么我不能克隆 ConcurrentHashMap

ConcurrentHashMap<String, String> test = new ConcurrentHashMap<String, String>();
    test.put("hello", "Salaam");

    ConcurrentHashMap<String, String> test2 = (ConcurrentHashMap<String, String> ) test.clone();

    System.out.println(test2.get("hello"));

如果我使用 HashMap 而不是 ConcurrentHashMap,它会起作用。

AbstractMap上的clone()方法不是用来复制的,它是一个内部方法,注意protected关键字。

protected Object clone() throws CloneNotSupportedException {

HashMap 恰好有一个 public clone(), 但这并不意味着你应该使用它,Effective Java: Analysis of the clone() method

对此进行了进一步讨论

创建集合副本的更灵活的方法是通过复制构造函数。这些具有从任何其他创建任何 Map 实现的优势。

/**
 * Creates a new map with the same mappings as the given map.
 *
 * @param m the map
 */
public ConcurrentHashMap(Map<? extends K, ? extends V> m) {

例如

ConcurrentHashMap<String, String> original = new ConcurrentHashMap<String, String>();
original.put("hello", "Salaam");

Map<String, String> copy = new ConcurrentHashMap<>(original);
original.remove("hello");
System.out.println(copy.get("hello"));

更优雅的方法是进行深度克隆。 如果您确实执行了深度克隆,那么可能会存在这样一种情况,您只复制存储在并发哈希图中的引用而不是实际对象。这就是为什么在这种情况下,首选深度克隆,其中克隆对象图中的对象。进行深度克隆的最简单方法之一是使用 apache 通用语言库 - SerializationUtils#clone。

<dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
    </dependency>

可以使用SerializationUtils class的clone api进行深度克隆,如下-

ConcurrentHashMap<String, Vertex> transposeVertexMap = (ConcurrentHashMap<String, Vertex>) SerializationUtils.clone(vertexMap);