[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