![JVM-GC垃圾回收算法-判定一個對象是否是可回收的對象](http://p2.ttnews.xyz/loading.gif)
GC的出現解放了程序員需要手動回收內存的苦惱,但我們也是要了解GC的,知己知彼,百戰不殆嘛。
常見的GC回收算法主要包括引用計數算法、可達性分析法、標記清除算法、複製算法、標記壓縮算法、分代算法以及分區算法。
其中,引用計數法和可達性分析法用於判定一個對象是否可以回收,其他的算法為具體執行GC時的算法。
今天來聊聊可達性分析法,並說明一下什麼樣的對象才是真正可以被回收的。
在介紹引用計數法的時候,我們提到了此種算法的循環引用的缺陷,所以Java沒有使用此種算法。
那Java使用的是啥算法來標記一個對象是否是垃圾對象呢?
Java是通過判斷一個對象是否可觸及,以及一個對象的引用類型(強引用、軟引用、弱引用、虛引用)來決定是否回收這個對象。
本文將根據上述,分為兩部分進行介紹。
最後會簡單介紹一下GC回收過程中保證數據一致性的方法:Stop the World
1 如何判斷一個對象是否可觸及?
判斷是否可觸及包含兩個要素:
(1)通過可達性分析該對象到GC Root不可達,如果不可達會進行第一次標記。
(2)已經喪失"自救"機會,如果沒有自救機會,會進行第二次標記,此時該對象可回收。
1.1可達性分析
可達性分析法定義了一系列稱為"GC Roots"的對象作為起始點,從這個起點開始向下搜索,每一條可達路徑稱為引用鏈,當一個對象沒有任意一條引用鏈可以到達"GC Roots"時,那麼就對這個對象進行第一次"可回收"標記。
那麼什麼是GC Root呢?
可以理解為由堆外指向堆內的引用。
那麼都有哪些對象可以作為GC Roots呢?
包括如下幾種
- 代碼中某一方法中的局部變量
- 類變量(靜態變量)
- 常量
- 本地方法棧中引用的對象
- 已啟動且未停止的線程
下面以一段代碼來簡單說明一下前三類
class Test {
private static A a = new A(); // 靜態變量
public static final String CONTANT = "I am a string"; // 常量
public static void main(String[] args) {
A innerA = new A(); // 局部變量
}
}
class A {
...
}
這段代碼的運行時內存圖示如下:
![JVM-GC垃圾回收算法-判定一個對象是否是可回收的對象](http://p2.ttnews.xyz/loading.gif)
內存圖示
首先,類加載器加載Test類,會初始化靜態變量a,將常量引用指向常量池中的字符串,完成Test類的加載;
然後,main方法執行,main方法會入虛擬機方法棧,執行main方法會在堆中創建A的對象,並賦值給局部變量innerA。
此時GC Roots狀態如下:
GC Roots
當main方法執行完出棧後,變為:
GC Roots
第三個對象已經沒有引用鏈可達GC Root,此時,第三個對象被第一次標記。
1.2對象的"自救"
一個被可達性分析標記為可回收的對象,是有機會進行自救的。前提是:覆寫了Object的finalize()方法,且GC還沒有執行該對象的finalize()方法。
先來看一下finalize方法的定義
/**
* Called by the garbage collector on an object when garbage collection
* determines that there are no more references to the object.
* A subclass overrides the {@code finalize} method to dispose of
* system resources or to perform other cleanup.
*
* The general contract of {@code finalize} is that it is invoked
* if and when the Java™ virtual
* machine has determined that there is no longer any
* means by which this object can be accessed by any thread that has
* not yet died, except as a result of an action taken by the
* finalization of some other object or class which is ready to be
* finalized. The {@code finalize} method may take any action, including
* making this object available again to other threads; the usual purpose
* of {@code finalize}, however, is to perform cleanup actions before
* the object is irrevocably discarded. For example, the finalize method
* for an object that represents an input/output connection might perform
* explicit I/O transactions to break the connection before the object is
* permanently discarded.
*
* The {@code finalize} method of class {@code Object} performs no
* special action; it simply returns normally. Subclasses of
* {@code Object} may override this definition.
*
* The Java programming language does not guarantee which thread will
* invoke the {@code finalize} method for any given object. It is
* guaranteed, however, that the thread that invokes finalize will not
* be holding any user-visible synchronization locks when finalize is
* invoked. If an uncaught exception is thrown by the finalize method,
* the exception is ignored and finalization of that object terminates.
*
* After the {@code finalize} method has been invoked for an object, no
* further action is taken until the Java virtual machine has again
* determined that there is no longer any means by which this object can
* be accessed by any thread that has not yet died, including possible
* actions by other objects or classes which are ready to be finalized,
* at which point the object may be discarded.
*
* The {@code finalize} method is never invoked more than once by a Java
* virtual machine for any given object.
*
* Any exception thrown by the {@code finalize} method causes
* the finalization of this object to be halted, but is otherwise
* ignored.
*
* @throws Throwable the {@code Exception} raised by this method
* @see java.lang.ref.WeakReference
* @see java.lang.ref.PhantomReference
* @jls 12.6 Finalization of Class Instances
*/
protected void finalize() throws Throwable { }
大致翻譯一下前兩段:當GC判定某一對象不再通過任一形式被引用時,GC會調用該對象的finalize方法。方法執行時,可以進行任何操作,包括將這個對象再次賦值給某一變量引用,但其主要目的還是做一些對象的清除操作。
其實在finalize方法中,只要將這個對象的引用(this)再次賦值給某一變量,這個對象就可以"自救"。
如果一個對象在finalize階段也沒有完成自救,那麼就真的要被回收了。
下面演示一個"自救"的例子:
public class SaveMe {
public static SaveMe saveMe;
public static void main(String[] args) throws InterruptedException {
saveMe = new SaveMe();
saveMe = null; // 取消引用,經過可達性分析,上面new出來的對象不再可達GC Root
System.gc(); // 第一次GC,會執行finalize方法
Thread.sleep(1000);
if (saveMe == null) {
System.out.println("對象為null");
} else {
System.out.println("對象不為null");
}
// 經過上面的過程,對象已經自救了,這裡再次將其引用置空
saveMe = null;
System.gc(); // 不會再執行finalize方法,沒有機會自救了
Thread.sleep(1000);
if (saveMe == null) {
System.out.println("對象為null");
} else {
System.out.println("對象不為null");
}
}
// finalize方法全局只會執行一次
@Override
protected void finalize() throws Throwable {
super.finalize();
saveMe = this; // 進行自救
}
}
上述代碼很簡明,可根據註釋理解。代碼執行結果如下:
運行結果
2 不同引用類型的回收
Java中有四種引用類型,引用強度由強到弱:強引用、軟引用、弱引用、虛引用。針對不同的引用類型,GC的回收策略不同。
2.1強引用
通過關鍵字new的對象就是強引用對象,強引用指向的對象任何時候都不會被回收,寧願OOM也不會回收。
2.2軟引用
如果一個對象持有軟引用,那麼當JVM堆空間不足時,會被回收。
一個類的軟引用可以通過java.lang.ref.SoftReference持有。
2.3弱引用
如果一個對象持有弱引用,那麼在GC時,只要發現弱引用對象,就會被回收。
一個類的弱引用可以通過java.lang.ref.WeakReference持有。
2.4虛引用
幾乎和沒有一樣,隨時可以被回收。
通過PhantomReference持有。
3 Stop the World
問題的出現:如果程序一邊執行,一邊進行可達性分析的標記操作,那麼有可能剛標記完一個對象,這個對象又再次被賦值給其他的引用。這樣就有可能回收掉正在使用的對象。
解決這個問題的方式就是Stop the World(STW),STW會在所有線程到達一個安全點時,暫停掉所有應用線程的執行,然後開始專心的標記垃圾對象。這樣就保證了數據的一致性,不會導致誤回收。
閱讀更多 Mr羽墨青衫 的文章