[英]class object referred by class loader?
why class objects are referred by class loader ? 为什么类对象被类加载器引用? should it not be other way around ie 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 ?
是否应该以其他方式绕过,即应该已经引用了类加载器,以便如果类对象不可访问且内存消耗较少,则该类对象可以成为GC的合格对象?
I know i am missing some thing basic here but not sure what. 我知道我在这里缺少一些基本的东西,但不确定是什么。 I tried googling it but could not find answered
我尝试使用Google搜索,但找不到答案
Because the ClassLoader
loads classes and its responsibility is to know what classes it has loaded. 因为
ClassLoader
加载类,所以它的责任是知道已加载了哪些类。 Class
objects also have a reference to the ClassLoader
that loaded it, hence the getClassLoader() method in Class
. Class
对象还引用了加载它的ClassLoader
,因此是Class
的getClassLoader()方法。
Memory consumption has absolutely nothing to do with anything here, I can't imagine why you would think it does. 内存消耗与此处的任何内容绝对无关 ,我无法想象您为什么会认为如此。
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. 如果查看类java.lang.ClassLoader的实现,您会发现Class对象的实际实例化发生在JVM的“幕后”。 Class information is obtained by native methods (eg findLoadedClass0) and ClassLoader invokes native method defineClass1 to define new class when necessary.
类信息是通过本机方法(例如findLoadedClass0)获得的,并且在必要时,ClassLoader调用本机方法defineClass1来定义新类。 How these methods are implemented depends on JVM.
这些方法的实现方式取决于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:
但是,正如州对java.lang.ClassLoader的源代码中的Vector类对象的注释:
// 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. 结果是,如果需要释放未使用的类定义的内存,则需要对ClassLoader本身进行GC。 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.
这正是JEE应用程序服务器和OSGi容器卸载Web应用程序和插件时发生的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.