Open In App

Java Runtime runFinalization() Method with Examples

Last Updated : 23 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, every object has a method called finalize(). Before reclaiming the memory that the actual object was exploited, the garbage collector calls this method. It provides an opportunity for an object to perform cleanup operations earlier than it is garbage collected.

However, the execution of finalize() is not secure, and it depends on when the garbage collector decides to collect the object. Sometimes, Garbage collection may not occur immediately in all cases, and as a result, the finalize() method might not be called promptly.

This is where the runFinalization() method acting comes into play.

Understanding runFinalization()

The runFinalization() method is a part of the Runtime class, and its purpose is to trigger the execution of the finalization methods of any objects that are awaiting finalization. Its sentence structure is as follows:

public void runFinalization()

Example of runFinalization():

Below is the implementation of the runFinalization() method:

Java




// Java Program to demonstrate
// runFinalization() Method
  
// Driver Class
public class FinalizationExample2 {
      // main function
    public static void main(String[] args) {
        // Creating a large number of objects
        for (int i = 0; i < 5; i++) {
            new ObjectWithFinalize();
        }
  
        // Running garbage collection explicitly
        System.gc();
  
        // Running finalization explicitly
        Runtime.getRuntime().runFinalization();
  
        // Printing a message after running finalization
        System.out.println("End of main");
    }
}
  
class ObjectWithFinalize {
    @Override
    protected void finalize() throws Throwable {
        System.out.println("Finalize method called");
    }
}


Output

Finalize method called
Finalize method called
Finalize method called
Finalize method called
Finalize method called
End of main




Explaintation of the above example

  • We create a large number of ObjectWithFinalize objects within the loop.
  • After that, we explicitly call System.gc() to suggest to the JVM to run the garbage collector.
  • Then, we run finalization explicitly using Runtime.getRuntime().runFinalization().

By explicitly triggering garbage collection (System.gc()), we increase the likelihood that the garbage collector will run, and subsequently, the finalize() methods of the objects in the finalization queue might be called.

Note: System.gc() doesn’t guaranteed that garbage collections is triggered. It will suggest JVM to do so.

Conclusion:

In conclusion, the runFinalization() method in Java, disunite of the java.lang.Runtime separate, is a tool that allows developers to explicitly run the finalisation methods of objects pending finalization. However, its usage comes with considerations and is a great deal irresolute in the privilege of letting the scrap collector finagle retentiveness automatically.

  • Garbage Collection Timing: The exact timing of scrap appeal and finalisation is not deterministic and depends on factors such as garbage collector execution, memory direction scheme, and usable system resources.
  • Non-Guaranteed Finalisation: The finalise() method acting on a very physical object is not guaranteed to be dead right away or at a specific clock; it will flush when runFinalisation() is explicitly named. The JVM has the discretion to adjudicate when it’s ready to run finalisation methods.
  • Automatic Memory Management: Java’s automatic retentivity management, including scraping, is designed to understate manual interference. Developers are pleased to bank on the JVM’s intrinsic mechanisms rather than attempt to verify the timing of finalisation explicitly.
  • Best Practices: If cleanup is necessary, alternative mechanisms such as try-with-resources or implementing the AutoCloseable user interface are suggested instead of relying on finalize().

In practice, explicit calls to runFinalization() and attempts to verify refuse collection are uncommon in well-designed Java applications. Developers typically focus on a piece of writing strip, resource-efficient code, and bank the JVM to wield memory management effectively. Understanding the principles of food waste appeal, finalisation, and choice resourcefulness management techniques is material for unrefined and effective Java programs.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads