Welcome 微信登录

首页 / 软件开发 / JAVA / Java虚拟机类型卸载和类型更新解析

Java虚拟机类型卸载和类型更新解析2011-01-03zhuxing首先看一下,关于java虚拟机规范中时如何阐述类型卸载(unloading)的:

A class or interface may be unloaded if and only if its class loader is unreachable. The bootstrap class loader is always reachable; as a result,system classes may never be unloaded.

Java虚拟机规范中关于类型卸载的内容就这么简单两句话,大致意思就是:只有当加载该类型的类加载器实例(非类加载器类型)为unreachable状态时,当前被加载的类型才被卸载.启动类加载器实例永远为reachable状态,由启动类加载器加载的类型可能永远不会被卸载.

我们再看一下Java语言规范提供的关于类型卸载的更详细的信息(部分摘录):

//摘自JLS 12.7 Unloading of Classes and Interfaces

1、An implementation of the Java programming language may unload classes.

2、Class unloading is an optimization that helps reduce memory use. Obviously,the semantics of a program should not depend on whether and how a system chooses to implement an optimization such as class unloading.

3、Consequently,whether a class or interface has been unloaded or not should be transparent to a program

通过以上我们可以得出结论: 类型卸载(unloading)仅仅是作为一种减少内存使用的性能优化措施存在的,具体和虚拟机实现有关,对开发者来说是透明的.

纵观java语言规范及其相关的API规范,找不到显示类型卸载(unloading)的接口,换句话说:

1、一个已经加载的类型被卸载的几率很小至少被卸载的时间是不确定的

2、一个被特定类加载器实例加载的类型运行时可以认为是无法被更新的

【类型卸载进一步分析】

前面提到过,如果想卸载某类型,必须保证加载该类型的类加载器处于unreachable状态,现在我们再看看有 关unreachable状态的解释:

1、A reachable object is any object that can be accessed in any potential continuing computation from any live thread.

2、finalizer-reachable: A finalizer-reachable object can be reached from some finalizable object through some chain of references, but not from any live thread. An unreachable object cannot be reached by either means.

某种程度上讲,在一个稍微复杂的java应用中,我们很难准确判断出一个实例是否处于unreachable状态,所 以为了更加准确的逼近这个所谓的unreachable状态,我们下面的测试代码尽量简单一点.