0

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?

RedCrafter LP
  • 174
  • 1
  • 8
  • 2
    It's possible, but certainly not with `Object`. – Louis Wasserman Jun 13 '22 at 17:47
  • Object is just an example could have used Foo. But they should be a static reference in the classloader as far as i know, so how can they ever get gc'ed? – RedCrafter LP Jun 13 '22 at 17:49
  • 1
    There's no such thing as "the" classloader. There can be more than one, and they can get GC'd themselves. – Louis Wasserman Jun 13 '22 at 18:06
  • But you can get the objects in a static fashion ```Object.class``` wouldn't that mean that they have a static reference? – RedCrafter LP Jun 13 '22 at 18:21
  • The ones that you get that way, sure. Not all `Class` objects are obtained with `Foo.class`. Look at the methods in `ClassLoader`, e.g. `defineClass`. – Louis Wasserman Jun 13 '22 at 18:58
  • That seems to be the answer to my question. "You can't rely on a java.lang.Class instance to be static". I am building some raw pointer stuff and was hoping to store the class as it's instance pointer as an long. But since I can't rely on the validity of that "blind" pointer I will need to reconsider my approach. Louise Wasserman thanks a lot. – RedCrafter LP Jun 13 '22 at 19:44
  • 1
    You can’t rely on the validity of any instance pointer. The garbage collector moves objects in memory. – Holger Jun 14 '22 at 07:37

1 Answers1

1

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).

Holger
  • 285,553
  • 42
  • 434
  • 765