Fundamentals 6 min read

Deep vs Shallow Copy in Java: Visualizing Object Instances with Heap Dumps

During a rewrite of a performance testing framework, the author explores Java deep and shallow copying, demonstrates memory analysis using heap dumps and JConsole to visualize object instances, and provides sample code illustrating how to clone objects safely across multiple threads.

FunTester
FunTester
FunTester
Deep vs Shallow Copy in Java: Visualizing Object Instances with Heap Dumps

When refactoring a performance‑testing framework, the author needed each thread to collect its own statistics. Using a shared threadbase object caused unsafe concurrent access, so the solution was to create a separate copy of the object for each thread.

Deep vs. Shallow Copy Theory

The author reviews the concepts of shallow and deep copying in Java. In theory, assigning an object ( a1 = a) creates only one heap instance, a shallow copy creates a second instance that shares referenced objects, and a deep copy creates a completely independent copy, including nested objects.

Test Code

package com.fun;

import com.fun.frame.SourceCode;
import java.io.Serializable;

public class AR extends SourceCode {
    public static void main(String[] args) {
        waitForKey("1");
        HeapDumper.dumpHeap("1", true);
        Tttt clone = tttt.clone();
        waitForKey("2");
        HeapDumper.dumpHeap("2", true);
        Tttt tttt1 = deepClone(tttt);
        HeapDumper.dumpHeap("3", true);
        waitForKey("3");
    }

    static class Tttt implements Cloneable, Serializable {
        public Sss sss = new Sss();
        private static final long serialVersionUID = 4989553780571753462L;
        public Tttt clone() {
            try {
                return (Tttt) super.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    static class Sss implements Cloneable, Serializable {
        private static final long serialVersionUID = -5487147719650620894L;
        public Sss clone() {
            try {
                return (Sss) super.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}

Heap Dump and Inspection

The program pauses three times, each pause marking a node. At each pause the author uses jconsolembean to trigger a heap dump via a custom HeapDumper.dumpHeap utility. The generated .hprof files are then examined with jhat -port 8001 <dumpfile>, which starts a local HTTP service (e.g., http://localhost:8001/) showing heap usage.

In the JHat UI, the user selects the desired class, clicks the instance tab, and sees the number of live objects.

Results

Images below display the instance counts for Tttt objects after each dump, confirming the expected 1, 2, and 3 instances.

Tttt instance counts
Tttt instance counts

Similarly, the Sss object counts are shown, matching the theoretical expectation of 1, 1, and 2 instances.

Sss instance counts
Sss instance counts

Conclusion

The experiment validates the theoretical differences between direct assignment, shallow copy, and deep copy in Java by visualizing actual heap objects. Using heap dumps and JHat provides a practical way to verify object lifecycles and memory usage during development.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javadeep copyMemory analysisshallow copyHeap DumpJConsole
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.