Finalize Method In Java

Finalize Method In Java: In this article, we will discuss theĀ Finalise Method In Java. As we know, when an object is no longer used, or there is no reference to an object, then that object becomes available for Garbage collection.

So before removing that object from the memory, the garbage collector calls the finalize() method in Java. When the GC calls the finalize () method, this method allows the object to perform the cleanup operation before the object is destroyed.

So, let us try to understand the Finalise Method in detail.

What is the finalize() method in Java?

The finalize method in Java is a special method the Java programming language provides to allow an object to perform cleanup operations before garbage is collected. Garbage collection is when the Java Virtual Machine (JVM) automatically reclaims memory that objects no longer use.

When an object becomes eligible for garbage collection, the JVM calls the finalize method (if the object’s class has overridden it) before reclaiming the memory occupied by that object. This allows the object to release any external resources it might have acquired during its lifetime, such as open files, network connections, or database connections.

Here are some key points about the finalize method in Java:

Inherited from java.lang.Object: The finalize method is defined in the java. lang.Object class, which is the root class for all Java classes. However, it’s important to note that the finalize method in Object does nothing and is an empty method. To enable custom cleanup behavior for an object, you must override the finalize method in your class and implement the cleanup logic specific to your object’s requirements.

Resource Cleanup: One common use of the finalize method is to release resources held by an object, such as closing open files or releasing network connections. This helps prevent resource leaks in your Java application.

Use with Caution: While the finalize method provides a mechanism for resource cleanup, it’s not the recommended way to manage resources in modern Java. Instead, it’s better practice to use explicit resource management techniques like try-with-resources or implementing the AutoCloseable interface for better control over resource cleanup.

Unpredictable Timing: The exact timing of when the JVM calls the finalize method is not guaranteed. It depends on the garbage collection process, which can vary. This unpredictability makes it less suitable for critical resource cleanup tasks.

Deprecation in Java 9: In Java 9 and later versions, the finalize() method has been deprecated, signaling a shift towards more predictable and efficient resource management practices.

The JEP-421 (Java 18) has marked the finalization deprecated. It will be removed in a future release. The use of Cleaners is recommended.

Syntax For Finalize Method In Java

The finalize method in Java has the following syntax:

protected void finalize() throws Throwable 
{
	// Cleanup and resource release code here
	// This can include closing files, releasing connections, etc.
	// It can also include other cleanup operations specific to the object.

	// Call the superclass finalize method
	super.finalize();
}

Let’s break down the syntax:

  • Access Modifier: The finalize method is typically declared with the protected access modifier. This is because it’s intended to be overridden by subclasses to provide custom cleanup logic.
  • Return Type: The finalize method has a return type of void, meaning it doesn’t return any value.
  • Method Name: It must be finalized, matching the method name in the java.lang.Object class.
  • Exception Handling: The finalize method is declared to throw Throwable. This is done to indicate that it can throw any kind of Throwable, including exceptions and errors. It’s important to handle any exceptions or errors that may occur during the cleanup process.
  • Method Body: Inside the finalize method, you should include the code for cleanup and resource release specific to your object. This can include closing files, releasing network connections, or any other cleanup operations needed. Ensuring that resources are properly released is crucial to avoid resource leaks.
  • Call to super.finalize(): As part of your finalize method, it’s a good practice to call the super.finalize() method. This ensures that any cleanup logic defined in the superclass’s finalize method is executed in the java.lang.Object class, the finalize method is empty, so calling super.finalize() in most cases has no effect. However, it’s a recommended practice for consistency and to allow for potential future changes in the superclass’s finalize method.

How does Override finalize the () method?

To override the finalize() method in Java, you need to follow these steps:

  • Create a Class: First, create a Java class in which you want to override the finalize() method. This class should extend a superclass (typically java.lang.Object or any class inheriting it).
  • Declare the finalize() Method: Within your class, declare the finalize() method with the same method signature as in the superclass (i.e., it should be named finalize() and have the protected access modifier, return type void, and throw Throwable).
  • Implement Cleanup Logic: Inside the finalize() method, write the cleanup logic specific to your class. This could include releasing resources like closing files, releasing network connections, or any other cleanup operations required.
  • Call super.finalize(): As part of your finalize() method, it’s a good practice to call super.finalize(). This ensures that any cleanup logic defined in the superclass’s finalize() method is also executed. In most cases, the java.lang.Object class’s finalize() method is empty, so calling super.finalize() has no effect. However, it’s a recommended practice for consistency.

Here’s an example of how to override the finalize() method in a Java class:

public class MyResourceCleanup extends Object 
{
	// Constructor and other class methods
	// Override the finalize method
	@Override
	protected void finalize() throws Throwable 
	{
		try 
		{
			// Cleanup logic specific to this class
			// For example, close files or release resources
		} 
		finally 
		{
			// Call the superclass finalize method
			super.finalize();
		}
	}
}

Finalize Method In Java Example

Here’s a simple Java program demonstrating how the finalize() method works. This program creates an object, overrides the finalize() method, and then shows how the finalize() method is called when the object becomes eligible for garbage collection:

public class FinalizeDemo 
{
	// A simple class with a finalize method
	static class MyObject
	{
		// Override the finalize method
		@Override
		protected void finalize() throws Throwable 
		{
			try 
			{
				System.out.println("Finalize method is called.");
				// Perform cleanup or resource release here
			} 
			finally 
			{
				super.finalize();
			}
		}
	}

	public static void main(String[] args) 
	{
		MyObject myObj = new MyObject();

		// Set the reference to null, making the object eligible for garbage collection
		myObj = null;

		// Suggesting the JVM to run garbage collection (Note: It's just a suggestion, not a command)
		System.gc();

		// Wait for a while to allow the finalize method to be called
		try 
		{
			Thread.sleep(1000);
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}

		System.out.println("Program finished.");
	}
}

Output:

Finalize method is called.
Program finished.

In this program:

  • We define a class MyObject with an overridden finalize() method. Inside the finalize() method, we print a message indicating the method is called. You can include your cleanup logic in this method.
  • In the main method, we create an instance of MyObject and then set the reference myObj to null. This makes the object eligible for garbage collection because no more references exist.
  • We suggest the JVM run garbage collection by calling System.gc(). Note that this is just a suggestion to the JVM, and the JVM manages the actual garbage collection process, so the timing of when the finalize() method is called is not guaranteed.
  • We introduce a delay with Thread.sleep(1000) to give the JVM some time to perform garbage collection and call the finalize() method.
  • After the delay, we print “Program finished” to indicate the program’s completion.

When you run this program, you’ll see that the finalize() method is called when the object is garbage collected, as indicated by the “Finalize method is called” message.

Conclusion:

we’ve explored Java’s finalize() method and its role in allowing objects to perform cleanup operations before garbage is collected. While this method can be used for resource management, it’s important to note that it’s not recommended in modern Java development. Instead, consider using more predictable and efficient resource management techniques such as try-with-resources or implementing the AutoCloseable interface.

If you have any doubts or questions about the finalize() method in Java, please feel free to ask in the comment section below. Additionally, if you have suggestions on improving this article or topics you’d like to see covered in more detail, your feedback is highly valuable. We encourage you to share your thoughts and suggestions in the comment section. Your input helps us provide better and more informative content.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment