Garbage collector example doesn't hold
i was reading the thinking in java chapter about the garbage collector,
and i found out an example which is running once upon a while. But i can't
figure out why.
public class Book {
boolean checkedOut = false;
Book(boolean checkOut) {
checkedOut = checkOut;
}
void checkIn() {
checkedOut = false;
}
@Override
protected void finalize() {
if (checkedOut) {
System.out.println("Error: checked out");
}
// Normally, you'll also do this:
//super.finalize(); // Call the base-class version
}
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();
}
}
The call to System.gc() should force finalization of objects even if the
memory is not running out.
Thus why the programs output Error: checked out only after 4-5 execution
in a row? i can't get the point, can you try to clarify it out please? I
expect that everytime the GC is called the finalize method is executed as
well, thus everytime the check out error should be promped.
Thanks
No comments:
Post a Comment