簡體   English   中英

Java GC 沒有清除 SoftReference

[英]SoftReference is not getting cleared by Java GC

我試圖理解 Java 中的SoftReferences ,它基本上確保在拋出StackOverflowError之前清除 SoftReferenced 對象的內存。

public class Temp 
{

    public static void main(String args[])
    {
        Temp temp2 = new Temp();
        SoftReference<Temp> sr=new SoftReference<Temp>(temp2);

        temp2=null;
        Temp temp=new Temp();
        temp.infinite(sr);

    }

    public void infinite(SoftReference sr)
    {

        try
        {
            infinite(sr);
        }
        catch(StackOverflowError ex)
        {
            System.out.println(sr.get());
            System.out.println(sr.isEnqueued());
        }

    }
}

然而上面的結果是

test.Temp@7852e922
false

有人能解釋一下為什么對象沒有被 GC 清除嗎? 我怎樣才能讓它工作?

看起來您可能對StackOverFlowErrorOutOfMemoryError有一些困惑。 StackOverFlowErrorOutOfMemoryError錯誤是不同的。 當調用堆棧中沒有空間時會發生StackOverFlowError :當 JVM 無法在堆空間中為新對象分配內存時,會發生OutOfMemoryError 您的代碼導致StackOverflow :這意味着堆棧內存已滿,而不是堆空間。 我相信會有足夠的空間來存儲您的SoftReference ,這就是它不 GCd 對象的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM