Tuesday, 8 December 2015

Java Runtime class


public class Runtime extends Object

The java.lang.Runtime class allows the application to interface with the environment in which the application is running.

It helps to us interact with java run-time environment. This class contains method to invoke Garbage Collector, free memory, total memory available or execute a process etc.

java.lang.Runtime class is a Singleton for a java application.

Some useful methods:
Method
Description
public static Runtime getRuntime()

Runtime is Singleton class.
This method returns the instance of Runtime class.

public void exit(int status)

This method terminates the currently running Java virtual machine by initiating its shutdown sequence.

public void addShutdownHook(Thread hook)

Registers new hook thread.
public Process exec(String command)throws IOException

Executes given command in a separate process.

public int availableProcessors()

Returns the number of available processors.

public long freeMemory()

Returns amount of free memory in JVM.

public long totalMemory()

Returns amount of total memory in JVM.

boolean removeShutdownHook(Thread hook)

This method de-registers a previously-registered virtual-machine shutdown hook.



Open Command prompt using exec() method
import java.io.IOException;
public class Test {
     public static voidmain(String[] args) throws Exception {
           Runtime rt = Runtime.getRuntime();
           try {
                rt.exec(new String[]{"cmd.exe","/c","start"});

           } catch (IOException e) {
           }
     }
}

Memory test using Runtime class:

public class Test {
     public static void main(String args[]) { 
           Runtime runtime = Runtime.getRuntime(); 
           System.out.println("Total Memory:"+runtime.totalMemory()); 
           System.out.println("Free Memory: "+runtime.freeMemory()); 

           for(inti=0;i<Integer.MAX_VALUE;i++){ 
                Object object = new Object(); 
           }
          
           System.out.println("After creating instance of Object");
           System.out.println("Free Memory: "+runtime.freeMemory());
          
           System.out.println("After calling gc()");
           System.gc();
           System.out.println("Free Memory: "+runtime.freeMemory()); 
     } 
}

Output:
Total Memory:61800448
Free Memory: 61476688
After creating instance of Object
Free Memory: 60996792
After calling gc()
Free Memory: 61335224

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...