Java Deep Copy using In-memory Serialization

We all know that the easiest way of deep cloning (with some performance overhead) or deep copy is serialization. Java serialization involves serializing the object into bytes and from bytes to the object again. We suggest using in-memory deep cloning whenever it is the only need and we …

java 8

We all know that the easiest way of deep cloning (with some performance overhead) or deep copy is serialization. Java serialization involves serializing the object into bytes and from bytes to the object again.

We suggest using in-memory deep cloning whenever it is the only need and we don’t need to persist the object for future use. In this Java deep cloning example, we will suggest one mechanism of in-memory deep cloning for our reference.

Please remember that deep cloning is evil for singleton pattern. It makes it possible to have multiple instances of singleton classes.

Read more : Object Cloning in Java

1. Java deep copy example

In the demo program, we have created a demo class named SerializableClass. This has three variables i.e. firstName, lastName and permissions. We will add a deepCopy() instance-level method to this class. Whenever invoked on an instance of SerializableClass, it will return an exact clone / deep copy of that instance.

For deep cloning, we have to first serialize and then perform deserialization. For serialization, we have used ByteArrayOutputStream and ObjectOutputStream. For deserialization, we have used ByteArrayInputStream and ObjectInputStream.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestClass implements Serializable {

  private static final long serialVersionUID = 1L;

  private String firstName;
  private String lastName ;
  private List permissions;

  public TestClass deepCopy() throws Exception {
    //Serialization of object
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bos);
    out.writeObject(this);

    //De-serialization of object
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    ObjectInputStream in = new ObjectInputStream(bis);
    TestClass copied = (TestClass) in.readObject();
    return copied;
  }
}

2. Demo

Let us test the class and create a deep copy of the instance to verify if it works as expected.

public class DeepCopyDemo {

  public static void main(String[] args) throws Exception {

    TestClass myClass = new TestClass("Lokesh", "Gupta", List.of("ADMIN", "USER"));

    System.out.println(myClass);

    TestClass deepCopiedInstance = myClass.deepCopy();

    System.out.println(deepCopiedInstance);
  }
}

Program Output.

TestClass(firstName=Lokesh, lastName=Gupta, permissions=[ADMIN, USER])
TestClass(firstName=Lokesh, lastName=Gupta, permissions=[ADMIN, USER])

Before considering in-memory deep copy objects in your application, you might like to read about serialization guidelines that will prevent your design from breaking in the future.

Happy Learning !!

Sourcecode on Github

Leave a Comment

  1. Excellent article! But, one query –
    In

     deepCopy() 

    method, you made a comment –

     //Verify that object is not corrupt 

    I wonder, what could possibly go wrong and what can we do to verify/tackle it?

    Reply
    • Rohit, program is very simple. In first program, Instead of writing the byte stream to any file/network resource, I am directly using to create another instance of class. This saved me lots of I/O operations.

      Second program is just an example for how to use code of first program.

      Reply
      • thanks for getting back, as we are not using lots of file I/O operations, I guess that is an advantage of deep cloning ? and why we are using deep cloning? I know its mentioned if we dont want to persist the object for future use but here we are creating another duplicate object . didnt get this part..

        Reply
      • Excellent article. But, one query –
        You have a comment in the code //Verify that object is not corrupt

        I wonder, what could possibly go wrong and how we verify/tackle it?

        Reply

Leave a Comment

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.