How can I implement destructors in Java?

Finlay McWalter

Generally, you won't need to - the most common usage of destructors in C++ is to free memory - and java will do that for you automatically via "garbage collection" (GC). :)

That said, if you have some other special resource to free or if you're curious as to when the GC runs, implement a finalize() method (protected void finalize()) which will be run when the GC is about to delete the object.

It's important to bear in mind that the finalizer is run when the GC frees your object, not when the object first becomes garbage (i.e. unreferenced) - depending on memory conditions inside the heap on your specific platform and the particulars of the runtime you use, it could be a very long time before the finalizer is called during a GC cycle.