首先看一下,關於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狀態,我們下面的測試代碼盡量簡單一點.