Java記憶體回收行程

來源:互聯網
上載者:User

記憶體回收行程只知道釋放那些由new分配的記憶體。一旦記憶體回收行程準備回收new對象,將首先調用finalize()方法,該方法能在記憶體回收時刻做一些清理工作。

這意味著在你不需要某個對象之前,如果必須執行某些動作,那麼你得自己去做(finalize()方法)。通常不能指望finalize(),必須建立其他的"清理"方法,並且明確的調用它們。finalize()作用:對象"終結條件"的驗證。

class finalizeTest...{
    public static void main(String[] args)...{
        Auto auto = new Auto();//當一個對象沒有被引用時才會成為垃圾,這一句的new對象不是垃圾。
        auto = null; //剛才的new對象成為垃圾。
        new Auto();
        new Auto();
        System.gc();
    }
}

class Auto...{
    public void finalize()...{
        System.out.println("Auto is going");
    }
}

ps:finalize()方法放在Auto類中,則new Auto()對象回收的時候會被調用;如果finalize()方法放在finalizeTest類中,則new Auto()對象回收的時候不會被調用,new finalizeTest()對象回收的時候才會被調用。

運行結果:

Auto is going
Auto is going
Auto is going

另外一個應用執行個體

 

class Book...{
    public boolean checkedout = false;
    public Book(boolean checkout)...{
        checkedout = checkout;
    }
    public void checkIn()...{
        checkedout = false;//狀態轉換 && 將checkedout變數歸位到false
    }
    public void finalize()...{
        if(checkedout)
            System.out.println("這本書沒有執行checkIn");
    }
    public static void main(String[] args)...{
        Book ThinkingInJava = new Book(true);
        ThinkingInJava.checkIn();
        
        Book DataStructure = new Book(true);
        DataStructure = null;
        System.gc();
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.