Search code examples
javaobjectreferencegarbage-collection

Are java.lang.Class objects ever garbage collected?


My question is if objects of type java.lang.Class ever gets garbage collected. Example:

WeakReference<Class<Object>> ref = new WeakReference<>(Object.class);
assertEquals(ref.get(),null);

Is this possible to ever assert to true? Can the reference to a java.lang.Class object ever get invalid?


Solution

  • A java.lang.Class is tied to the class it represents. The garbage collection of the Class instance implies unloading the class, which is possible, but only under certain circumstances. For a normal class or interface, it requires not only the Class object but also its defining ClassLoader instance to become unreachable, which in turn requires all classes of this particular class loader to be unreachable.

    That’s addressed in the specification in §12.7. Unloading of Classes and Interfaces:

    An implementation of the Java programming language may unload classes.

    A class or interface may be unloaded if and only if its defining class loader may be reclaimed by the garbage collector as discussed in §12.6.

    Classes and interfaces loaded by the bootstrap loader may not be unloaded.

    All Built-in Class Loaders will never become unreachable.

    But there’s also the defineHiddenClass method which allows to define special, “hidden” classes which may get garbage collected even if their defining loader is reachable (unless the STRONG option has been specified).