We've moved! — MindVault360 is now HexLab. Better design, more content & premium notes.

Visit HexLab →

MindVault360 has moved!

We've upgraded to HexLab — a faster, more professional platform with better content, premium notes, and a modern design.

Visit us at hexlab

Tuesday, September 10, 2024

Java Runtime class


(Tap the post to see more)


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);

}

}

← Back Next →

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home