Reputation: 10530
why class objects are referred by class loader ? should it not be other way around i.e. class loader should have been referred so that class object could have become eligible for GC if class object is unreachable and lesser memory consumption ?
I know i am missing some thing basic here but not sure what. I tried googling it but could not find answered
Upvotes: 0
Views: 138
Reputation: 662
If you look at implementation of class java.lang.ClassLoader, you will find that actual instantiation of Class objects happens "behind the scenes" by JVM. Class information is obtained by native methods (e.g. findLoadedClass0) and ClassLoader invokes native method defineClass1 to define new class when necessary. How these methods are implemented depends on JVM.
Thus, it's not necessary to maintain these references for the purposes of object instantiation. However, as states comment to the Vector of Class objects in the source code of java.lang.ClassLoader:
// The classes loaded by this class loader. The only purpose of this table
// is to keep the classes from being GC'ed until the loader is GC'ed.
// private final Vector<Class<?>> classes = new Vector<>();
The consequence is that if you need to free memory of unused Class definitions, you need to GC the ClassLoader itself. It's possible if there's no object containing a reference to any of the classes loaded by that class loader and you can just forget the reference to that class loader. This is exactly what's happening in JEE application servers and OSGi containers when they unload web applications and plugins.
Upvotes: 0
Reputation: 73568
Because the ClassLoader
loads classes and its responsibility is to know what classes it has loaded. Class
objects also have a reference to the ClassLoader
that loaded it, hence the getClassLoader() method in Class
.
Memory consumption has absolutely nothing to do with anything here, I can't imagine why you would think it does.
Upvotes: 2