[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
本文探讨了Java中垃圾回收的工作原理,解释了它与C++析构函数的不同之处,并通过一个图书管理示例展示了如何使用finalize()方法来检测对象是否已正确清理。此外,还讨论了几种垃圾回收方案。

1353

被折叠的 条评论
为什么被折叠?



