48

In Java, there are special objects called Garbage Collection Roots (GC roots). They serve as a root objects for Garbage Collection marking mechanism (see picture).

enter image description here

This article describes four types of GC roots:

  • local variables
  • active threads
  • static variables
  • JNI references

It is also mentioned, that:

Classes themselves can be garbage-collected.

GC roots aren't collected thus classes themselves are not GC roots.

So what are GC roots for the classes?

1
  • 1
    The GC roots are those that you listed for everything. Your question really is about what kind of objects typically hold references to class objects.
    – biziclop
    Nov 28, 2014 at 10:40

2 Answers 2

33

So what are GC roots for the classes?

Classloaders, effectively - via other GC roots.

If there is nothing which can reach a classloader - which means nothing can reach any classes created by that classloader or any instances of those classes - then both the classloader and the classes it created are eligible for garbage collection. Keeping them alive until then is necessary so that Class::forName and ClassLoader::findClass can be idempotent even when the class's static initializers are not.

Hidden classes (see https://openjdk.java.net/jeps/371) are exceptions to this rule. As an implementation detail of OpenJDK, so are the classes of method references, lambdas, and proxies created with the static methods of java.lang.reflect.Proxy. The classloader does not hold a strong reference to these classes.

4
  • classloader instance resides at heap? Dec 28, 2016 at 16:34
  • 1
    @gstackoverflow: Well they're certainly not on the stack. Which precise part of the heap is a different matter.
    – Jon Skeet
    Dec 28, 2016 at 17:50
  • @gstackoverflow: Well that's part of the heap. That's what I mean by "which precise part of the heap is a different matter"....
    – Jon Skeet
    Dec 28, 2016 at 21:21
  • 2
    just official oracle documentation call permgen as part of heap, but usually in community heap = [young gen] + [old gen] Dec 29, 2016 at 7:41
20

A garbage collection root is an object that is accessible from outside the heap.

Memory Analyzer categorizes garbage collection roots according to the following list:

  1. Class loaded by system ClassLoader
    • static field in JDK classes(java.* etc)
  2. Live thread
    • stack -local vars, method params
    • java.lang.Thread instance
  3. Object held as synchronization monitor
  4. JNI references
  5. JVM specials...

Source 1 Source 2

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.