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 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

Comments

Subscribe
Notify of
guest
9 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

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.