File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes serialization instead of cloning? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "serialization instead of cloning?" Watch "serialization instead of cloning?" New topic

serialization instead of cloning?

Masa Saito

Joined: Jun 08, 2010
Posts: 14
Using Serialization over piped streams I believe I can perform deep copy (cloning).
Is this correct? Here is a code snippet:

Twisting together piped streams in the same thread is prone to deadlock as per javadoc.
But that aside, "cloneObj" is a clone of "originalObj" in 100% everyway, right?
Should this be considered a valid technique in production code? If not, why not?
A senior developer informed me that the fathers of Java intended serialization to only be used to persist an object outside the jvm. Using the twisted pipes technique was wrong because it violates the "intended use" of serialization and he refused to discuss any further.

What says the Java Ranch? Serialization is deep copy. Clone is deep copy. I can serialize to perform cloning. right?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

It's not particularly elegant or efficient, but I've done it sometimes because I had to. If performance doesn't matter much, but simplicity does, then it's a good strategy.

[Jess in Action][AskingGoodQuestions]
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3028
Masa Saito wrote:Serialization is deep copy. Clone is deep copy. I can serialize to perform cloning. right?

By default, no - clone() uses shallow copy. If you want deep copy, using serialization is worth considering. It you don't want to carefully modify the clone() method of each class accordingly, and you haven't yet determined that performance is poor and this is the primary bottleneck, then this is a good way to achieve your objectives, in my opinion.

As for your use of piped streams, it seems like this is an unrelated consideration. On one hand, you can choose between using clone() or using serialization. On another hand, completely independent, you can choose between writing to a piped stream, or a ByteArrayOutputStream, or a file, or something else. The first is a choice of what format to use; the latter is a choice of destination. The first is what to write, and the latter is where to write it. As far as I can see here, the two choices are independent and unrelated.
I agree. Here's the link:
subject: serialization instead of cloning?
jQuery in Action, 3rd edition