How do I define destructors?
Java does no destructors
, but you can use Object # finalize () method as work.
The Java programming language does not guarantee which thread will invoke the finalize method on any given object. It is guaranteed, however, that the thread that calls the termination will not have user-dependent synchronization locks when finalize is called. If a thrown exception is thrown by the finalize method, the exception is ignored and the completion of this object ends.
class Book {
@Override
public void finalize() {
System.out.println("Book instance is getting destroyed");
}
}
class Demo {
public static void main(String[] args) {
new Book();//note, its not referred by variable
System.gc();//gc, won't run for such tiny object so forced clean-up
}
}
output:
Book instance is getting destroyed
Runs the garbage collector. The call to gc shows that the Java Virtual Machine is spending effort recycling unused objects in order to make the memory they currently occupy reuse. When control returns from a method call, the Java Virtual Machine has made every effort to free up space from any discarded objects.
Calling System.gc () is actually equivalent to calling:
Runtime.getRuntime (). Ds ()
Called by the garbage collector on an object during garbage collection, determines that there are no more references to the object. The subclass overrides the finalization method to utilize system resources or perform other cleanup.
source to share