Is there a destructor for Java? Is there a destructor for Java? java java

Is there a destructor for Java?


Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.

There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error).

There was a question that spawned in-depth discussion of finalize recently, so that should provide more depth if required...


Have a look at the try-with-resources statement. For example:

try (BufferedReader br = new BufferedReader(new FileReader(path))) {  System.out.println(br.readLine());} catch (Exception e) {  ...} finally {  ...}

Here the resource that is no longer needed is freed in the BufferedReader.close() method. You can create your own class that implements AutoCloseable and use it in a similar fashion.

This statement is more limited than finalize in terms of code structuring, but at the same time it makes the code simpler to understand and maintain. Also, there is no guarantee that a finalize method is called at all during the livetime of the application.


Nope, no destructors here. The reason is that all Java objects are heap allocated and garbage collected. Without explicit deallocation (i.e. C++'s delete operator) there is no sensible way to implement real destructors.

Java does support finalizers, but they are meant to be used only as a safeguard for objects holding a handle to native resources like sockets, file handles, window handles, etc. When the garbage collector collects an object without a finalizer it simply marks the memory region as free and that's it. When the object has a finalizer, it's first copied into a temporary location (remember, we're garbage collecting here), then it's enqueued into a waiting-to-be-finalized queue and then a Finalizer thread polls the queue with very low priority and runs the finalizer.

When the application exits, the JVM stops without waiting for the pending objects to be finalized, so there practically no guarantees that your finalizers will ever run.