gpt4 book ai didi

java - 加速 java 深度复制操作

转载 作者:搜寻专家 更新时间:2023-10-31 19:42:02 25 4
gpt4 key购买 nike

我们已经使用序列化实现了通用深度复制机制。

import java.io.*;

public class CopyUtil {

public static Object clone(Object source) {
Object retVal = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(source);
oos.flush();
oos.close();

ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
retVal = in.readObject();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}

return retVal;
}
}

有相对大量的对象类,它们一直在进化,需要维护——这就是我们采用通用克隆机制的原因。我们不喜欢在 200 多个类上维护 readObject()writeObject() 的想法。

不幸的是,Java 中的序列化机制相对较慢,当我们的系统处于峰值负载时,我们会遇到问题。

是否有任何关于我们如何加快速度或(如果我们执行不正确)克隆对象的替代方法的建议方法?

最佳答案

Hibernate 中实现了一种比序列化更快的替代方法(特别是在二级缓存中);我不知道细节,但你可以查看源代码。

您可能会意识到 clone() 接口(interface)已损坏,因此最好避免使用它,除非有真正令人信服的理由使用它。来自 Effective Java 2nd Edition ,第 11 条:明智地覆盖克隆

Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.

更新:关于浅/深克隆

来自 the clone() API :

Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. [...]

By convention, the object returned by this method should be independent of this object (which is being cloned). To achieve this independence, it may be necessary to modify one or more fields of the object returned by super.clone before returning it. Typically, this means copying any mutable objects that comprise the internal "deep structure" of the object being cloned and replacing the references to these objects with references to the copies. If a class contains only primitive fields or references to immutable objects, then it is usually the case that no fields in the object returned by super.clone need to be modified.

所以其实约定俗成就是做深拷贝。

不过,首选的替代方法是定义复制构造函数或独立方法,而不是重写 clone()

关于java - 加速 java 深度复制操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3627053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com