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. The current runtime can be obtained from the getRuntime
method. It provides methods to execute system processes, obtain information about the runtime environment, and manage system resources.
Java application cannot create its own instance of this class.
Executing System Processes
The exec()
method of the Runtime
class allows you to execute system commands or launch external applications.
Example: Running a Command
public class ExecuteCommand {
public static void main(String[] args) {
try {
// Execute a system command
Process process = Runtime.getRuntime().exec("ls -l");
// Process the output if needed
} catch (IOException e) {
e.printStackTrace();
}
}
}
Getting the Runtime Object
You can obtain the Runtime
object using the getRuntime()
method.
Example:
public class GetRuntimeObject {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
System.out.println("Available processors: " + runtime.availableProcessors());
}
}
Terminating the JVM
The exit()
method of the Runtime
class allows you to terminate the JVM.
Example:
public class TerminateJVM {
public static void main(String[] args) {
Runtime.getRuntime().exit(0);
}
}
Freeing Memory
The gc()
method suggests the JVM to run the garbage collector.
Example:
public class FreeMemory {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
runtime.gc();
}
}
Adding Shutdown Hook
The addShutdownHook()
method allows you to register a shutdown hook to be executed when the JVM is shutting down.
Example:
public class ShutdownHookExample {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
runtime.addShutdownHook(new Thread(() -> {
// Perform cleanup tasks before JVM shutdown
}));
}
}
Code to run Music
public class AudioPlayer {
public static void main(String[] args) {
try {
// Path to the audio file
String audioFilePath = "/path/to/audio.mp3";
// Open the audio file with the default system player
Process process = Runtime.getRuntime().exec("open " + audioFilePath); // for mac
Process process = Runtime.getRuntime().exec("cmd /c start " + audioFilePath); // for windows
process.waitFor(); // Wait for the process to complete
} catch (Exception e) {
e.printStackTrace();
}
}
}
Code to run Video
public class VideoPlayer {
public static void main(String[] args) {
try {
// Path to the video file
String videoFilePath = "C:\\path\\to\\video.mp4";
// Open the video file with the default system player
Process process = Runtime.getRuntime().exec("open " + videoFilePath); // for mac
Process process = Runtime.getRuntime().exec("cmd /c start " + videoFilePath); // for windows
process.waitFor(); // Wait for the process to complete
} catch (Exception e) {
e.printStackTrace();
}
}
}