Runtime class in Java

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running.

How to get the current Runtime

The current runtime can be obtained from the static getRuntime method.

Runtime runtime = Runtime.getRuntime();

APIs in Runtime
Runtime class in Java
package com.java.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RuntimeExample {

    public static void main(String[] args) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        System.out.println("Total Memory:" + runtime.totalMemory());
        System.out.println("Free Memory:" + runtime.freeMemory());
        System.out.println("Max Memory:" + runtime.maxMemory());
        System.out.println("Available Processors:" + runtime.availableProcessors());
        runtime.addShutdownHook(new Thread(() - > {
            System.out.println("JVM Shutting Down");
        }));
        // Execute "ls" command
           
        String str;    
        Process p;    
        try {      
            p = runtime.exec("ls");      
            BufferedReader br = new BufferedReader(        new InputStreamReader(p.getInputStream()));      
            while ((str = br.readLine()) != null)         System.out.println(str);      
            p.waitFor();      
            p.destroy();    
        } catch (Exception e) {}
        runtime.gc();
        System.out.println("Free Memory after GC:" + runtime.freeMemory());
        runtime.exit(0);
    }

}
Total Memory:257425408
Free Memory:254741016
Max Memory:3817865216
Available Processors:12
bin
src
Free Memory after GC:255497656
JVM Shutting Down

Leave a Reply

Your email address will not be published. Required fields are marked *