|
|
|
|
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:
which on the surface sounds like a kind of destructor.
In fact, using finalizers is usually more grief than it's worth. Why?
finally block:
// Allocate resource here.
try
{
// Use resource here
}
finally
{
// Release resource here
}
By placing the code to release a resource in a
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 |