Runtime is a singleton class in Java. You can perform below tasks using Runtime class.
  • Execute any OS command – exec()
  • Find free memory – freeMemory()
  • Find total memory – totalMemory()
  • Terminate the Java application – exit()
  • Get the count of processors available to JVM – availableProcessors()
Below example demonstrates Runtime usage.

package runtime;

/**
 * Created by Sagar on 16-04-2016.
 */
public class RuntimeTest {

    public static void main(String [] args)throws Exception{
        Runtime runtime=Runtime.getRuntime();
        System.out.println("Count of Processors -> "+runtime.availableProcessors());
        System.out.println("Total Memory -> "+runtime.totalMemory());
        System.out.println("Free Memory -> "+runtime.freeMemory());
        //Launch calculator using exec. You can execute any command using exec
        Process calculatorProcess = runtime.exec("calc.exe");
        //Program will continue running until you close the calculator
        calculatorProcess.waitFor();
        runtime.exit(0);

    }
} 
Here is the output of above example.

Count of Processors -> 4
Total Memory -> 56623104
Free Memory -> 54190136

Web development and Automation testing

solutions delivered!!