Java Destructor – finalize()

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags with 2 Comments on Java Destructor – finalize()

Concept of destructor in JAVA. finalize() method.

Java Destructor finalize()
Java Destructor finalize()

The aim of destructor in any OOPs language is:

  1. Free up the memory (c++ suffer from memory allocation / deallocation)
  2. Clean up any other resources (like closing of open file stream)

Java take cares of all and hence there is no destructor in Java. (With the help of Garbage collection)
but still if you want to perform some additional tasks, then you can use the finalize() method of java.

But, we can’t rely on finalize() as it depends on GC. Sometimes, GC may never be invoked during the lifetime of the program. A good idea is to implement a method, say cleanUp() which does, any special processing required, ofcourse, other than freeing up memory. The programmer should call this method at the approppriate place in the program. That is the only way to make sure your program works correctly.

Example code of finalize in java:

class Thing {

	public static int number_of_things = 0;
	public String what;

	public Thing (String what) {
	        this.what = what;
	        number_of_things++;
	        }

	protected void finalize ()  {
	        number_of_things--;
	        }
	}

public class TestDestructor {
	public static void main(String[] args)
	{
		Thing obj = new Thing("Test App");

	}
}

Related posts

2 thoughts on “Java Destructor – finalize()”

  1. Yes this is the only way i could cleanup my OpenGL textures. on every CTOR the reference counts are incremented and on finalized they are decremented. upon count == 0, i release those textures. Anyway GC saves us from a lot of trouble, but no destructor is very compromising as well.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.