Chapter 16 of 26

Object Lifecycle & Memory

Every object in a program has a life story. It is born when memory is reserved and a constructor runs, it lives while the program uses it, and it dies when its memory is given back. Who decides when an object dies is one of the biggest differences between languages like Java, C++ and Python.

In the Constructors & Destructors chapter we looked at the code that runs at the start and end of an object's life. In this chapter we zoom out and look at the whole journey: where objects live in memory, how references keep them alive, how garbage collection decides an object is dead, why memory leaks still happen in Java, and how C++ and Python handle the same problem differently.

The object lifecycle is the sequence of stages an object goes through: memory allocation, initialization, use, becoming unreachable (or being explicitly destroyed), cleanup, and finally deallocation of its memory.


The Stages of an Object's Life

Here is the life of a Java object created with new Student("Asha"):

 1. Allocation      JVM reserves memory on the heap; fields get default values (0, false, null)
        │
        ▼
 2. Initialization  field initializers + constructor run; object is now in a valid state
        │
        ▼
 3. In use          reachable through one or more references; methods are called on it
        │
        ▼
 4. Unreachable     no chain of references leads to it any more
        │
        ▼
 5. Collected       garbage collector reclaims the memory (at a time the JVM chooses)

In C++ the picture is almost the same, except stages 4 and 5 are replaced by an explicit moment of destruction: the object's destructor runs at a known point in the code (end of scope or delete), and its memory is freed right after.

Why does this matter? Because the stages tell you when you can rely on cleanup. Memory is cleaned up automatically in Java, but files, sockets and database connections are not memory, and they need a different strategy. We will come back to this.


Where Objects Live: Stack vs Heap

A running program usually uses two important areas of memory:

Feature

Stack

Heap

What is stored

Method call frames: local variables, parameters, return addresses

Objects (in Java: every object and array)

Lifetime

Ends automatically when the method returns

Until the object is collected (Java/Python) or deleted (C++)

Allocation speed

Very fast (move a pointer)

Fast in modern JVMs, but needs management later

Size

Small, one stack per thread

Large, shared by all threads

Typical error

StackOverflowError (deep recursion)

OutOfMemoryError (too many live objects)

In Java, a statement like this involves both areas:

Student s = new Student("Asha");
      STACK (main's frame)                 HEAP
   ┌──────────────────────┐        ┌───────────────────────┐
   │ s : reference ───────┼──────▶ │ Student object        │
   └──────────────────────┘        │   name ──▶ "Asha"     │
                                   └───────────────────────┘

The variable s is not the object. It is a reference (think of it as an address) stored in the stack frame. The object itself lives on the heap. When main returns, s disappears, but the object stays on the heap until the garbage collector decides it is no longer needed.

C++ is more flexible: the same class can be created on the stack (Student s("Asha");) or on the heap (new Student("Asha")). Python is like Java: every value, even an integer, is an object on the heap, and variables are just names bound to objects.

A small but interview-worthy detail: modern JVMs perform escape analysis. If the JIT compiler proves that an object never leaves a method, it may avoid allocating it on the heap at all (for example by keeping its fields in registers). This is an optimization you cannot see from your code; the language rule is still "objects live on the heap".


References and Reachability

Java and Python decide whether an object is alive using one idea:

An object is alive if it is reachable: there is a chain of references leading to it from a GC root. An object with no such chain is garbage and may be reclaimed.

GC roots are references that are alive by definition. The most common ones are:

  • Local variables and parameters in the stack frames of running threads

  • static fields of loaded classes

  • Active threads themselves, and references held by native code (JNI)

Notice that "reachable" is about chains. If root → A → B → C, then C is alive even though no local variable points to it directly.

Worked Example: Watching Objects Become Unreachable

public class LifecycleDemo {

    static class Student {
        String name;

        Student(String name) {
            this.name = name;
            System.out.println("Constructed: " + name);
        }
    }

    static Student topper;   // a static field is a GC root

    static void createTemporary() {
        Student temp = new Student("Ravi");
        System.out.println("Inside method, temp = " + temp.name);
    }   // 'temp' disappears here; the Ravi object becomes unreachable

    public static void main(String[] args) {
        Student a = new Student("Asha");    // 1. reference a -> Asha
        Student b = a;                      // 2. b points to the SAME object
        b.name = "Asha K";
        System.out.println("a.name = " + a.name);

        a = null;                           // Asha still reachable through b
        System.out.println("b.name = " + b.name);

        b = new Student("Meera");           // now nothing points to Asha K
        System.out.println("Asha K is now unreachable (eligible for GC)");

        createTemporary();                  // Ravi is unreachable after return

        topper = b;                         // Meera stays alive via a static field
        b = null;
        System.out.println("topper = " + topper.name);
    }
}

Output:

Constructed: Asha
a.name = Asha K
b.name = Asha K
Constructed: Meera
Asha K is now unreachable (eligible for GC)
Constructed: Ravi
Inside method, temp = Ravi
topper = Meera

Let us trace what happens to each object:

Step

References

Status

Student b = a;

a and b → Asha

One object, two references. Changing b.name is visible through a.

a = null;

b → Asha K

Still reachable through b.

b = new Student("Meera");

b → Meera

Asha K is unreachable: eligible for GC.

createTemporary() returns

temp's stack frame is gone

Ravi is unreachable.

topper = b; b = null;

static field topper → Meera

Meera stays alive for the life of the class (static field is a GC root).

There are three common ways an object becomes eligible for garbage collection:

  1. Nulling the reference: a = null;

  2. Reassigning the reference: b = new Student("Meera");

  3. The reference going out of scope: a local variable when its method returns.

Note the word eligible. Becoming unreachable does not mean the memory is freed immediately. The JVM collects garbage when it decides to, usually when the heap is filling up. Calling System.gc() is only a request; the JVM may ignore it.


How Garbage Collection Works (The Idea)

Real collectors such as G1 (the default collector since Java 9 on typical server and desktop machines), ZGC or Shenandoah are complex, but they are built on a few simple ideas.

Mark and Sweep

Mark phase:   start from every GC root and follow every reference,
              marking each object you reach as "live".

Sweep phase:  every object that was NOT marked is garbage;
              reclaim its memory.

Roots ──▶ [A] ──▶ [B]          [D] ◀──▶ [E]      [F]
           live    live          garbage cycle    garbage

Notice that D and E point to each other but nothing reachable points to them. A tracing collector like this frees them without any trouble. Cycles are not a problem for tracing garbage collection, which is a common interview trap.

Many collectors also compact the heap: they move live objects together so that free memory is one big block. This is possible in Java because your code never sees raw addresses, only references the JVM can update.

Generations

Studies of real programs show that most objects die young (temporary strings, iterators, request objects). So collectors such as G1 divide the heap into a young generation, collected often and quickly, and an old generation for objects that survived several collections, collected less often. This is called the generational hypothesis.

Reference Counting (Python's Main Strategy)

A different approach is to keep, inside each object, a count of how many references point to it. When the count drops to zero, the object is freed immediately. CPython (the standard Python interpreter) uses reference counting as its main mechanism, plus a separate cycle detector, because reference counting alone can never free a cycle (each object in the cycle keeps the other's count above zero).

import gc


class Node:
    def __init__(self, name):
        self.name = name
        self.partner = None
        print(f"created {name}")

    def __del__(self):
        print(f"destroyed {self.name}")


print("-- reference counting --")
a = Node("A")
b = a            # two references to the same object
del a            # one reference left: nothing happens
print("deleted a")
del b            # count drops to zero: destroyed immediately
print("deleted b")

print("-- reference cycle --")
x = Node("X")
y = Node("Y")
x.partner = y
y.partner = x    # X and Y now point to each other
del x, y         # counts never reach zero because of the cycle
print("deleted x and y")
gc.collect()           # the cycle detector finds and frees them
print("gc.collect() done")

Output (CPython 3.14):

-- reference counting --
created A
deleted a
destroyed A
deleted b
-- reference cycle --
created X
created Y
deleted x and y
destroyed X
destroyed Y
gc.collect() done

Look at the order of lines: destroyed A appears before deleted b. The moment the last reference disappeared, the object was destroyed. For the cycle, nothing happened at del x, y; the objects were only freed when the cycle detector ran. (In normal programs the cycle detector runs automatically from time to time; we called it manually to make the output predictable.)

Feature

Tracing GC (Java)

Reference counting (CPython)

When is memory freed?

Later, when the collector runs

Immediately when count hits 0

Cycles

Handled naturally

Need an extra cycle detector

Cost

Periodic work, possible pauses

Small cost on every reference assignment

Predictable cleanup?

No

Mostly yes (except cycles)


Cleanup of Non-Memory Resources

Garbage collection manages memory only. An object may also hold an open file, a network socket or a database connection. These are limited operating-system resources, and you cannot wait an unknown amount of time for the GC to release them.

Why Not finalize()?

Early Java offered Object.finalize(), a method the GC would call before reclaiming an object. It turned out to be a bad idea:

  • There is no guarantee when, or even whether, it runs.

  • It slows down garbage collection and can accidentally bring an object back to life ("resurrection").

  • Exceptions thrown inside it are silently ignored.

It has been deprecated since Java 9, and since Java 18 (JEP 421) it is deprecated for removal. Do not use it in new code.

The Right Tool: try-with-resources

Java's answer is deterministic cleanup: the class implements AutoCloseable, and the caller uses try-with-resources. The close() method is guaranteed to run when the block ends, even if an exception is thrown.

public class TryWithResourcesDemo {

    static class FileHandle implements AutoCloseable {
        private final String name;

        FileHandle(String name) {
            this.name = name;
            System.out.println("Open  " + name);
        }

        void write(String text) {
            System.out.println("Write \"" + text + "\" to " + name);
        }

        @Override
        public void close() {
            System.out.println("Close " + name);
        }
    }

    public static void main(String[] args) {
        try (FileHandle log = new FileHandle("log.txt");
             FileHandle data = new FileHandle("data.csv")) {
            log.write("started");
            data.write("1,2,3");
            throw new IllegalStateException("something went wrong");
        } catch (IllegalStateException e) {
            System.out.println("Caught: " + e.getMessage());
        }
        System.out.println("Both files were closed before the catch block ran");
    }
}

Output:

Open  log.txt
Open  data.csv
Write "started" to log.txt
Write "1,2,3" to data.csv
Close data.csv
Close log.txt
Caught: something went wrong
Both files were closed before the catch block ran

Two important details are visible here: resources are closed in reverse order of opening (data.csv first), and they are closed before the catch block runs.

A Safety Net: Cleaner

If a class wraps a native resource, Java 9+ offers java.lang.ref.Cleaner as a modern replacement for finalize(). The recommended pattern is: still implement AutoCloseable, but also register a cleanup action that runs if the user forgets to call close() and the object becomes unreachable.

import java.lang.ref.Cleaner;

public class CleanerDemo {

    private static final Cleaner CLEANER = Cleaner.create();

    // The cleanup state must NOT refer back to the Connection object,
    // otherwise the Connection could never become unreachable.
    private static class State implements Runnable {
        private final String id;

        State(String id) { this.id = id; }

        @Override
        public void run() {
            System.out.println("Releasing native socket for " + id);
        }
    }

    static class Connection implements AutoCloseable {
        private final Cleaner.Cleanable cleanable;

        Connection(String id) {
            this.cleanable = CLEANER.register(this, new State(id));
            System.out.println("Connected " + id);
        }

        @Override
        public void close() {
            cleanable.clean();   // runs State.run() at most once
        }
    }

    public static void main(String[] args) {
        try (Connection c = new Connection("db-1")) {
            System.out.println("Using connection");
        }
        System.out.println("Done");
    }
}

Output:

Connected db-1
Using connection
Releasing native socket for db-1
Done

Here the cleanup ran because close() called cleanable.clean(). If a careless user had never closed the connection, the Cleaner would run the same action at some point after the object became unreachable. The cleanup state is a separate static class on purpose: if it held a reference to the Connection, the connection would always be reachable and would never be cleaned.


Memory Leaks in a Garbage-Collected Language

Many students believe "Java has GC, so Java cannot leak memory". That is false. The GC frees unreachable objects. If your code accidentally keeps a reference to objects it will never use again, they stay reachable and are never freed.

In Java, a memory leak means objects that are no longer needed but are still reachable.

import java.util.ArrayList;
import java.util.List;

public class LeakDemo {

    // A "cache" that only ever grows: every object added stays reachable
    private static final List<byte[]> CACHE = new ArrayList<>();

    static void handleRequest(int id) {
        byte[] buffer = new byte[1024 * 1024];   // 1 MB of work data
        CACHE.add(buffer);                        // bug: never removed
    }

    public static void main(String[] args) {
        int i = 0;
        try {
            while (true) {
                handleRequest(i++);
            }
        } catch (OutOfMemoryError e) {
            int handled = CACHE.size();
            CACHE.clear();                        // free memory so we can print
            System.out.println("Requests handled: " + handled);
            System.out.println("Error: " + e);
        }
    }
}

Run with a small heap (java -Xmx64m LeakDemo). Output on our machine:

Requests handled: 31
Error: java.lang.OutOfMemoryError: Java heap space

The exact number depends on heap size and JVM version, but the program always runs out of memory, because every buffer is still reachable from the static CACHE list (a GC root). Common real-world causes of leaks are:

  • Static collections that only grow (caches without a size limit or eviction).

  • Listeners or callbacks that are registered but never removed.

  • Objects stored in a HashMap with keys whose hashCode() changes, so they can never be found and removed.

  • ThreadLocal values in thread pools that are never cleared.


C++: Deterministic Destruction and RAII

C++ has no garbage collector. Instead, every object has a precisely defined lifetime that depends on its storage duration:

Storage

How created

When destroyed

Automatic

Local variable: Tracer a("a");

At the end of its enclosing block, in reverse order of creation

Dynamic

new Tracer("x")

Only when you call delete (or a smart pointer does it for you)

Static

Global or static variable

After main ends

Because destruction happens at a known time, C++ uses the RAII idiom (Resource Acquisition Is Initialization): acquire a resource in the constructor and release it in the destructor. The resource is then released automatically when the object goes out of scope, even if an exception is thrown. Smart pointers apply RAII to heap memory.

#include <iostream>
#include <memory>
#include <string>

class Tracer {
    std::string name;
public:
    explicit Tracer(std::string n) : name(std::move(n)) {
        std::cout << "  ctor " << name << '\n';
    }
    ~Tracer() {
        std::cout << "  dtor " << name << '\n';
    }
};

Tracer global("global");   // static storage: lives for the whole program

int main() {
    std::cout << "main starts\n";
    {
        Tracer a("a");                 // automatic (stack) storage
        Tracer b("b");
        std::cout << "  end of block\n";
    }                                  // destroyed here, in reverse order: b, a

    Tracer* raw = new Tracer("raw");   // dynamic (heap) storage
    delete raw;                        // YOU must free it, exactly once

    {
        auto owner = std::make_unique<Tracer>("unique");
        auto moved = std::move(owner); // ownership transferred, no copy
        std::cout << "  owner is " << (owner ? "set" : "empty") << '\n';
    }                                  // 'moved' frees the object here

    std::shared_ptr<Tracer> s1 = std::make_shared<Tracer>("shared");
    {
        std::shared_ptr<Tracer> s2 = s1;
        std::cout << "  use_count = " << s1.use_count() << '\n';
    }
    std::cout << "  use_count = " << s1.use_count() << '\n';
    s1.reset();                        // last owner gone -> destroyed now

    std::cout << "main ends\n";
}

Compiled with g++ -std=c++23. Output:

  ctor global
main starts
  ctor a
  ctor b
  end of block
  dtor b
  dtor a
  ctor raw
  dtor raw
  ctor unique
  owner is empty
  dtor unique
  ctor shared
  use_count = 2
  use_count = 1
  dtor shared
main ends
  dtor global

Points to notice:

  • a and b are destroyed in reverse order (b, then a) at the closing brace.

  • The raw new/delete pair works, but forgetting delete leaks memory and calling it twice is undefined behavior. Modern C++ code rarely writes delete by hand.

  • std::unique_ptr has exactly one owner. Ownership can be moved, never copied.

  • std::shared_ptr keeps a reference count (just like CPython); the object dies when the last shared_ptr lets go. Like any reference counting, two objects that hold shared_ptrs to each other form a cycle that is never freed, which is why std::weak_ptr exists.

  • The global object is constructed before main and destroyed after it.


Java vs C++ vs Python at a Glance

Question

Java

C++

Python (CPython)

Where do objects live?

Heap

Stack, heap or static storage (your choice)

Heap

Who frees memory?

Tracing garbage collector

You, or RAII / smart pointers

Reference counting + cycle detector

Is destruction time known?

No

Yes

Usually (not for cycles)

End-of-life hook

close() via try-with-resources; Cleaner as safety net

Destructor ~ClassName()

with statement / __exit__; __del__ (not reliable)

Typical memory bug

Leak through forgotten references

Leak, dangling pointer, double delete

Leak through forgotten references or cycles with __del__ in old versions


Common Mistakes

  • Confusing the reference with the object. a = null does not destroy anything; it only removes one path to the object.

  • Believing System.gc() forces collection. It is only a hint.

  • Using finalize() or Python's __del__ to close files. Use try-with-resources in Java and with in Python.

  • Saying "Java cannot have memory leaks". Reachable-but-useless objects are leaks.

  • Saying "GC cannot free cyclic references". That is true only for pure reference counting; tracing collectors like the JVM's free cycles easily.

  • Returning a pointer or reference to a local variable in C++. The local is destroyed when the function returns, leaving a dangling pointer.


Interview Questions

When does an object become eligible for garbage collection in Java?

When it is no longer reachable from any GC root (local variables of live threads, static fields, active threads, JNI references). Typical ways: setting the reference to null, reassigning it, or the reference going out of scope. Eligible does not mean collected immediately.

Two objects refer to each other and nothing else refers to them. Will Java collect them?

Yes. Java uses tracing (reachability) garbage collection, so an unreachable cycle is garbage like any other unreachable object. Only pure reference counting has trouble with cycles.

What is the difference between stack and heap memory?

The stack holds method frames (locals, parameters) and is freed automatically when a method returns; it is small and per-thread. The heap holds objects, is shared by threads, and is managed by the garbage collector (Java) or by the programmer (C++).

Why is finalize() deprecated, and what should you use instead?

Its timing is unpredictable, it may never run, it slows the GC and can resurrect objects. Use AutoCloseable with try-with-resources for deterministic cleanup, and java.lang.ref.Cleaner as a safety net for native resources.

What is RAII?

Resource Acquisition Is Initialization: a C++ idiom where a resource is acquired in a constructor and released in the destructor, so the resource's lifetime is tied to an object's scope and is released automatically, even when exceptions occur.

How can a Java program run out of memory if it has a garbage collector?

If it keeps references to objects it no longer needs (for example in a static list or an unremoved listener), those objects stay reachable and the GC is not allowed to free them.


Summary

  • An object is allocated, initialized, used, becomes unreachable (or is explicitly destroyed) and is finally reclaimed.

  • References live on the stack; Java objects live on the heap.

  • Java's GC frees objects that are not reachable from GC roots; it handles cycles and runs when the JVM decides.

  • CPython frees objects as soon as their reference count hits zero, with a separate collector for cycles.

  • C++ destroys objects at well-defined points; RAII and smart pointers make cleanup automatic.

  • Release files and connections with try-with-resources, not finalize(); leaks in Java come from forgotten references.

We saw that two references can point to the same object. That raises a practical question: when you want a copy of an object, what exactly gets copied? That is the topic of the next chapter, Shallow Copy vs Deep Copy.