Java Destructor – finalize()

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");

	}
}

Posted

in

by

Tags:


Related Posts

Comments

2 responses to “Java Destructor – finalize()”

  1. Jscooter Avatar
    Jscooter

    Get with the times, it’s “Java” and not “JAVA”.

  2. bindesh singh Avatar
    bindesh singh

    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 to bindesh singhCancel reply

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

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading