Close

Java - System.runFinalization() Examples

Java Java API 


Class:

java.lang.System

java.lang.Objectjava.lang.Objectjava.lang.Systemjava.lang.SystemLogicBig

Method:

public static void runFinalization()

Runs the finalization methods of any objects pending finalization.


Examples


package com.logicbig.example.system;

public class RunFinalizationExample {

public static void main(String... args) {
for (int i = 1; i < 11; i++) {
MyClass myClass = new MyClass(i);
System.out.printf("MyClass created, c= %s%n",
myClass.getC());
System.gc();
System.runFinalization();
}
}

public static class MyClass {
private final int c;

public MyClass(int c) {
this.c = c;
}

public int getC() {
return c;
}

/**
* This method will be Called by the garbage collector
* before removing this object from the memory.
*/
@Override
protected void finalize() throws Throwable {
System.out.printf("-- %s is getting garbage collected --%n", c);
}
}

}

Output

MyClass created, c= 1
MyClass created, c= 2
-- 1 is getting garbage collected --
MyClass created, c= 3
-- 2 is getting garbage collected --
MyClass created, c= 4
-- 3 is getting garbage collected --
MyClass created, c= 5
-- 4 is getting garbage collected --
MyClass created, c= 6
-- 5 is getting garbage collected --
MyClass created, c= 7
-- 6 is getting garbage collected --
MyClass created, c= 8
-- 7 is getting garbage collected --
MyClass created, c= 9
-- 8 is getting garbage collected --
MyClass created, c= 10
-- 9 is getting garbage collected --
-- 10 is getting garbage collected --




Without runFinalization call.

package com.logicbig.example.system;

public class RunFinalizationExample2 {

public static void main(String... args) {
for (int i = 1; i < 11; i++) {
RunFinalizationExample.MyClass myClass =
new RunFinalizationExample.MyClass(i);
System.out.printf("MyClass created, c= %s%n",
myClass.getC());
System.gc();
}
}
}

Output

MyClass created, c= 1
MyClass created, c= 2
MyClass created, c= 3
MyClass created, c= 4
MyClass created, c= 5
-- 2 is getting garbage collected --
MyClass created, c= 6
-- 4 is getting garbage collected --
MyClass created, c= 7
-- 5 is getting garbage collected --
MyClass created, c= 8
-- 6 is getting garbage collected --
MyClass created, c= 9
-- 7 is getting garbage collected --
MyClass created, c= 10
-- 8 is getting garbage collected --
-- 9 is getting garbage collected --
-- 3 is getting garbage collected --
-- 1 is getting garbage collected --
-- 10 is getting garbage collected --




See Also