We have implemented a general purpose deep copy mechanism using serialization.
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;
}
}
There are a relatively large number of object classes, that are evolving all the time, to maintain – This was the reason why we proceeded with a general purpose cloning mechanism. We didn’t relish the idea of maintaining readObject() and writeObject() on 200+ classes.
Unfortunately the serialization mechanism in Java is relatively slow and we are experiencing issues when our system is under peak load.
Are there any suggested approaches on how we can speed things up a bit or (in case we have carried this out incorrectly) alternative methods of cloning objects?
A much faster alternative to serialization is implemented in Hibernate (specifically in the 2nd level cache); I don’t know the details but you can check out the source code.
You may be aware that the
clone()interface is broken, thus is better avoided, unless there is a really really compelling reason to use it. From Effective Java 2nd Edition, Item 11: Override clone judiciouslyUpdate: On shallow/deep cloning
From the clone() API:
So in fact, the convention is to do a deep copy.
Still, the preferred alternative is to define a copy constructor or an independent method instead of overriding
clone().