Video in progress

Strong Junior ⚙️ JVM and memory

Which objects become eligible for GC after this method finishes?

static final List<String> CACHE = new ArrayList<>();

void process() {
    StringBuilder temp = new StringBuilder("x");
    List<String> list = new ArrayList<>();
    list.add("a" + System.nanoTime());
    String keep = "b" + System.nanoTime();
    CACHE.add(keep);
}

temp and the objects inside list become unreachable as soon as the method returns. The String added to CACHE stays alive through the static field, and the GC will not touch it.

📖 Answer

The GC does not ask "is this object still needed?". It asks "can this object be reached from a GC root?" GC roots are local variables on thread stacks, static fields, JNI references and a few others.

While the method runs, temp, list and keep are roots on the stack. Once the method returns, the frame is gone:

  • the StringBuilder is held by nobody else, so it is eligible for collection;
  • the ArrayList and the "a..." string inside it are eligible too;
  • the "b..." string is still reachable through the static CACHE field, so it stays alive.

One caveat: "eligible for collection" does not mean "deleted right now". The JVM decides when the GC runs.

This very example is the most common shape of a memory leak: adding to a static collection and never removing anything. On prod, a CACHE like this fills the heap within a few days.