Finalizers
Home ] Up ] What is a Class? ] What is an Instance? ] Class Members ] Methods and Overloading ] Instance Creation ] Instance Destruction ] [ Finalizers ] Class Variables and Methods ] Wrapper Classes ]

 

 

It's true that, in Java, you usually don't need a class destructor, because allocated memory is automatically de-allocated by the Java garbage collector.  However, sometimes you need to free up a different kind of resource -- for example, file descriptors, GUI Windows, database handles, or network sockets, etc.

It is possible to write a finalize method for the class:
protected void finalize() throws Throwable
{ /* ... */ }
which on the surface sounds like a kind of destructor.

In fact, using finalizers is usually more grief than it's worth.  Why?

  • The time of instance garbage collection is not deterministic.
    • It's done in a separate, low-priority thread.  
    • In fact, depending on the program and the platform, the instance may never be destroyed!
  • Even if the instance does get garbage collected, this is done in a separate thread, and can (and often does) raise serious synchronization problems and can cause deadlocks.  These are very tricky to debug, and hard to fix, even once you've found the problem.
  • In short, don't use a finalizer where you would use a destructor in C++.  
  • In fact, in most cases, don't use a finalizer at all!
Instead, what is typically done to reliably release resources in Java is to use a finally block:
// Allocate resource here.
try
{
    // Use resource here
}
finally
{
    // Release resource here
}

By placing the code to release a resource in a finally block, you ensure that it will get executed whether the code runs successfully, or whether it throws an exception.

Note: There is a similar problem with releasing resources in C++, when exceptions are thrown:
Resource rsc = new Resource()
// ...
// <code that uses the resource, 
//  potentially throwing an exception>
// ...
delete rsc; 
// Only executes if no exception is thrown
 

This page was last modified on 02 October, 2007