Java System.runFinalization() – Examples

In this tutorial, we will learn about the Java System.runFinalization() function, and learn how to use this function to run finalize methods of all objects pending finalization, with the help of examples.

runFinalization()

System.runFinalization() runs the finalization methods of any objects pending finalization.

Syntax

The syntax of runFinalization() function is

</>
Copy
runFinalization()

Returns

The function returns void.

Example 1 – runFinalization()

In this example, we will demonstrate the difference between calling System.runFinalization() method and not calling this System.runFinalization() method, and how runFinalization() method runs finalize() methods for the objects that are pending finalization.

In the following example, we create Car objects in a loop. After an iteration is completed, the Car object car created in the loop is no longer used by the program. We are calling System.gc() inside the for loop, may clear the object from memory during garbage collection. Also System.gc() runs the finalize() method before clearing the object from memory. But, it is not mandatory for System.gc() to run garbage collection immediately after the object is deemed no more useful. Since we are calling System.runFinalization(), all the objects pending for finalization, which are Car objects in this case, shall have their finalize() methods run.

Java Program

</>
Copy
public class Example {
	public static void main(String args[]) {
		for (int i = 1; i < 5; i++) {
			Car car = new Car(i);
			System.out.println("Car-" + i + " created");
			System.gc();
			System.runFinalization();
		}
		System.gc();
		System.runFinalization();
	}
}

class Car {
	int number;

	public Car(int i) {
		number = i;
	}

	@Override
	protected void finalize() {   
		System.out.println("Car " + this.number + " destroyed");   
	}  
}

Output

Car-1 created
Car-2 created
Car 1 destroyed
Car-3 created
Car 2 destroyed
Car-4 created
Car 3 destroyed
Car 4 destroyed

The following program demonstrates what happens if we are not calling System.runFinalization() method. System.gc() runs the Garbage Collector on its own terms, not necessarily right after the object becomes useless for the program.

Java Program

</>
Copy
public class Example {
	public static void main(String args[]) {
		for (int i = 1; i < 5; i++) {
			Car car = new Car(i);
			System.out.println("Car-" + i + " created");
			System.gc();
		}
		System.gc();
	}
}

class Car {
	int number;

	public Car(int i) {
		number = i;
	}

	@Override
	protected void finalize() {   
		System.out.println("Car " + this.number + " destroyed");   
	}  
}

Output

Car-1 created
Car-2 created
Car-3 created
Car-4 created
Car 1 destroyed
Car 3 destroyed
Car 4 destroyed
Car 2 destroyed

Conclusion

In this Java Tutorial, we have learnt the syntax of Java System.runFinalization() function, and also learnt how to use this function with the help of examples.