Friday 10 August 2018

jcmd: GC.run_finalization: java.lang.System.runFinalization()

'GC.run_finalization' command is used to call java.lang.System.runFinalization()

As per the java documentation, whenever you call 'java.lang.System.runFinalization()', it suggests that the Java Virtual Machine expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations.

Example
HelloWorld.java

import java.util.Date;

public class HelloWorld {
 public static void main(String args[]) throws Exception {
  Thread t1 = new Thread() {
   public void run() {
    int count = 0;
    while (true) {
     count++;

     for (int i = 0; i < 100000; i++) {
      Employee emp = new Employee();
      emp.id = count + " : " + i;
      emp.name = "name " + emp.id;
     }

     try {
      Thread.sleep(1000);

      if (count % 5 == 0) {
       System.runFinalization();
      }

     } catch (Exception e) {

     }
    }
   }
  };

  System.out.println("Application started at : " + new Date());
  t1.start();
 }

 public static class Employee {
  private String id;
  private String name;

  @Override
  protected void finalize() throws Throwable {
   System.out.println(new Date() + ", Calling finalize method for id (" + id + "), name (" + name + ")");
  }
 }
}

Compile HelloWorld.java

Run HelloWorld.java using below command.
java -classpath . HelloWorld > finalize.txt

Open finalize.txt, you can see below kind of messages.

Application started at : Thu Jul 26 15:34:21 IST 2018
Thu Jul 26 15:34:23 IST 2018, Calling finalize method for id (1 : 39), name (name 1 : 39)
Thu Jul 26 15:34:23 IST 2018, Calling finalize method for id (1 : 697), name (name 1 : 697)
Thu Jul 26 15:34:23 IST 2018, Calling finalize method for id (1 : 825), name (name 1 : 825)
Thu Jul 26 15:34:23 IST 2018, Calling finalize method for id (1 : 946), name (name 1 : 946)
Thu Jul 26 15:34:23 IST 2018, Calling finalize method for id (1 : 1140), name (name 1 : 1140)
Thu Jul 26 15:34:23 IST 2018, Calling finalize method for id (1 : 1318), name (name 1 : 1318)
Thu Jul 26 15:34:23 IST 2018, Calling finalize method for id (1 : 1729), name (name 1 : 1729)
Thu Jul 26 15:34:23 IST 2018, Calling finalize method for id (1 : 2173), name (name 1 : 2173)
...................
...................
...................
...................




Previous                                                 Next                                                 Home

No comments:

Post a Comment