TIJ Note - Garbage collection

[the content of this article is summaried from Thinking In Java]

1)      Your object might not get garbage collected

All is controlled by JVM

2)      Garbage collection is not destructions

3)      Garbage collection is only about memory

 

You can do some cleanup in C++ destructor, but in Java that is another story. The gc will free memory, any cleanup is supposed to placed in finalize().

 

Finalize() is not guaranteed, is JVM isn’t close to running out of memory, it will not perform garbage collection

So do not rely on finalize() being called

 

Use finalize() to discover termination condition

//: c04:TerminationCondition.java

// Using finalize() to detect an object that

// hasn't been properly cleaned up.

 

class Book {

  boolean checkedOut = false;

  Book(boolean checkOut) {

    checkedOut = checkOut;

  }

  void checkIn() {

    checkedOut = false;

  }

  public void finalize() {

    if(checkedOut)

      System.out.println("Error: checked out");

    //nomally, you'll also do this, but requre exception handling

    //super.finalize();

  }

}

public class TerminationCondition {

  public static void main(String[] args) {

    Book novel = new Book(true);

    // Proper cleanup:

    novel.checkIn();

    // Drop the reference, forget to clean up:

    new Book(true);

    // Force garbage collection & finalization:

    System.gc();

  }

} ///:~

 

Garbage collection schemes

1)      reference counting

2)     (java) adaptive scheme: track live object from the reference in stack and static storage

stop-and-copy, mark-and-sweep

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值