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?