Java Runtime class


Java Runtime class

Java Runtime class is used to interact with java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory etc. There is only one instance of java.lang.Runtime class is available for one java application.


Example 01:


package com.java.Multi_threading;

public class RuntimeExample {

public static void main(String[] args) {

// Get the singleton instance of the Runtime class

Runtime runtime = Runtime.getRuntime();


// Get information about memory usage

long freeMemory = runtime.freeMemory();

long totalMemory = runtime.totalMemory();

long maxMemory = runtime.maxMemory();


System.out.println("Free Memory: " + freeMemory + " bytes");

System.out.println("Total Memory: " + totalMemory + " bytes");

System.out.println("Max Memory: " + maxMemory + " bytes");


// Execute an external process (e.g., listing files in the current directory)

try {

Process process = runtime.exec("ls");

int exitCode = process.waitFor(); // Wait for the process to finish


System.out.println("External process exited with code: " + exitCode);

} catch (Exception e) {

e.printStackTrace();

}


// Register a shutdown hook

runtime.addShutdownHook(new Thread(() -> {

System.out.println("Shutdown hook executed");

}));


// Demonstrate halting the JVM (commented out for safety)

// runtime.halt(0);

}

}

Post a Comment

0 Comments