Java虛擬機器-GC垃圾回收演算法-判定一個物件是否是可回收的物件

Mr羽墨青衫發表於2019-01-18

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 {
    ...
}
複製程式碼

這段程式碼的執行時記憶體圖示如下:

Java虛擬機器-GC垃圾回收演算法-判定一個物件是否是可回收的物件
首先,類載入器載入Test類,會初始化靜態變數a,將常量引用指向常量池中的字串,完成Test類的載入; 然後,main方法執行,main方法會入虛擬機器方法棧,執行main方法會在堆中建立A的物件,並賦值給區域性變數innerA。

此時GC Roots狀態如下:

Java虛擬機器-GC垃圾回收演算法-判定一個物件是否是可回收的物件
當main方法執行完出棧後,變為:

Java虛擬機器-GC垃圾回收演算法-判定一個物件是否是可回收的物件
第三個物件已經沒有引用鏈可達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.
* <p>
* The general contract of {@code finalize} is that it is invoked
* if and when the Java&trade; 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.
* <p>
* The {@code finalize} method of class {@code Object} performs no
* special action; it simply returns normally. Subclasses of
* {@code Object} may override this definition.
* <p>
* 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.
* <p>
* 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.
* <p>
* The {@code finalize} method is never invoked more than once by a Java
* virtual machine for any given object.
* <p>
* 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; // 進行自救
    }
}
複製程式碼

上述程式碼很簡明,可根據註釋理解。程式碼執行結果如下:

Java虛擬機器-GC垃圾回收演算法-判定一個物件是否是可回收的物件

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會在所有執行緒到達一個安全點時,暫停掉所有應用執行緒的執行,然後開始專心的標記垃圾物件。這樣就保證了資料的一致性,不會導致誤回收。

相關文章