Question

I need to deep-copy Java objects for one of my projects; and I was wondering if it's okay to use Serialization for this.

The objects are fairly small (< 1kb each), total #objects per copy would be < 500, and the copy routine will be invoked a few times a day. In this case, will it be okay to use Serialization for this in production, or is that still a really bad idea given the performance of Serialization?

If it's still a bad idea, I can think of using copy constructor/static copy method per such class to improve performance. Are there any other ways for it?

Was it helpful?

Solution

Maybe. Performance will not be an issue - dependencies will be.

The usual problem with serialization is that an innocent reference to some core class in your application can give you a copy of 90% of all the life instances because they suddenly become reachable. So you must be really careful with transient and the references which you use.

Worse, if you need serialization for deep copy and real state saving, you might end up with incompatible goals:

  • Deep copy needs to be fast
  • Deep copy can handle open resources (database connections)
  • State saving needs to handle API evolution (the state is stored on disk, it could be restored with a new version of the code).
  • State saving can benefit from using a readable form (so a human could fix mistakes)

Therefore, it's often better to use copy constructors than using a "clever hack" even though it might safe you some/a lot of time right now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top