I came across this question and am looking for some ideas?
You do not need (nor should you try to use) destructors - or what they are called in Java: "Finalizers".
The VM specification does allow for VM implementations to never call them. So they are not reliable for resource releases and the like. Generally speaking the code in the finalize()
method of any object can be called by the VM before the object is garbage collected, but as this is not mandatory, you should avoid it.
Java is garbage-collected, so there is no way to tell when your destructor would be called (when your object will be garbage-collected).
There is a finalize
(inherited) method but you can't rely on that for the exact reasons above (you can't predict when -and if- it will be called).
If you just need to cleanup some resources, you can call Runtime.getRuntime().addShutdownHook
Automatic object "destruction" in Java never happens at a guaranteed time. The only grantees for garbage collection are that before an object is collected the finalizer method will be called. Of course the garbage collector is never guaranteed to run, or do anything when it does run. So there is no guarantee that the finalize method will be called.
If you want to simulate C++ destructors in Java the best way is to use the following idiom (there are variations when it comest to exception handling - I'll just show the simplest case here):
final Resource r;
r = new Resource();
try
{
r.use();
}
finally
{
r.cleanup();
}
where the "cleanup" method is the "destructor".
This is more like the C++ Resource Acquisition Is Initialization idiom which is really for stack based objects, but isn't as nice.
Since others are talking about normal cases.. There are special cases where you want to create destroy()
, destruct()
, releaseExternalResources()
, shutdown()
etc. methods that should be actively called by the entity that controls the life cycle of that instance.
For example, an object can be an ActiveObject, which has live threads in it. In this case, you want to shut them down because else you will have memory leaks.
While one may not call that a destructor...
On a sidenote, I guess that interview question was intended as a trick question!