Login with  Log in with facebook
Hiring Manager? SIGN UP HERE

any good example to use finalize()?

Rishi Yadav
08/07/2011 at 22:52
1 Answer

When the garbage collector is ready to release the storage used for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the object’s memory. So if you choose to use finalize( ), it gives you the ability to perform some important cleanup at the time of garbage collection.

There is an interesting use of finalize( ) that does not rely on it being called every time. This is the verification of the termination condition of an object.

//: initialization/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;


protected void finalize() {


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

// Normally, you’ll also do this:

// super.finalize(); // Call the base-class version



public class TerminationCondition {

public static void main(String[] args) {

Book novel = new Book(true);

// Proper cleanup:


// Drop the reference, forgetto clean up:

new Book(true);

// Force garbage collection & finalization:



} /* Output:

Error: checked out



The termination condition is that all Book objects are supposed to be checked in before they are garbage collected, but in main( ), a programmer error doesn’t check in one of the books. Without finalize( ) to verify the termination condition, this can be a difficult bug to find.

Swaroop Vincent
08/08/2011 at 04:07

If you want to post any answer to this forum then you need to log in.
Schedule a Demo

Schedule a Demo with us

Name *
Email *
Phone *
Company *