Friday 10 August 2018

jcmd : GC.run: Call garbage collector

jcmd provides GC.run command to request garbage collection process.

Let me explain with an example.

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

     Employee emp = new Employee();
     emp.id = count;
     emp.name = "name " + count;

     try {
      Thread.sleep(1000);
     } catch (Exception e) {

     }
    }
   }
  };

  t1.start();
 }

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

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

Compile and run HeloWorld.java.

Open command prompt and execute ‘jcmd’ command.
C:\>jcmd
21712 sun.tools.jcmd.JCmd
13220
9752 HelloWorld

As you see above output, HelloWorld application is running with process id 9752.


Execute the command ‘jcmd 9752 help’ to check whether GC.run is available for this application or not.


As you see above image, ‘GC.run’ command is available for this application.

Execute the command ‘jcmd 9752 GC.run’


C:\>jcmd 9752 GC.run
9752:

Command executed successfully

You can able to see below kind of messages in HelloWorld console.
C:\Users\krishna\Documents>java -classpath . HelloWorld
Calling finalize method for id : 147, name : name 147
Calling finalize method for id : 146, name : name 146
Calling finalize method for id : 145, name : name 145
Calling finalize method for id : 144, name : name 144
Calling finalize method for id : 143, name : name 143
Calling finalize method for id : 142, name : name 142
Calling finalize method for id : 141, name : name 141
Calling finalize method for id : 140, name : name 140
Calling finalize method for id : 139, name : name 139
Calling finalize method for id : 138, name : name 138
Calling finalize method for id : 137, name : name 137
Calling finalize method for id : 136, name : name 136
Calling finalize method for id : 135, name : name 135
Calling finalize method for id : 134, name : name 134
Calling finalize method for id : 133, name : name 133
Calling finalize method for id : 132, name : name 132
Calling finalize method for id : 131, name : name 131
Calling finalize method for id : 130, name : name 130
Calling finalize method for id : 129, name : name 129
Calling finalize method for id : 128, name : name 128
Calling finalize method for id : 127, name : name 127
Calling finalize method for id : 126, name : name 126
Calling finalize method for id : 125, name : name 125
Calling finalize method for id : 124, name : name 124
Calling finalize method for id : 123, name : name 123
..............
..............
..............



Previous                                                 Next                                                 Home

No comments:

Post a Comment