Java Runtime Class
Introduction
The Java Runtime class allows the application to interface with the environment in which the application is running.
Class Declaration
Following is the declaration for java.lang.Runtime class −
public class Runtime extends Object
Class methods
Methods inherited
This class inherits methods from the following classes −
- java.lang.Object
Example: Adding Shutdown Hook to a Thread Object
The following example shows the usage of Java Runtime addShutdownHook() method. In this program, we've created one static inner class Message which is extending Thread. In main method, we've registered a shutdown hook with a new Message object using addShutdownHook() method. Then we kept system to sleep for 2 seconds and then printed a closing message. As shutdown hook is registered with Message object, its run method is called when program exits.
package com.tutorialspoint;
public class RuntimeDemo {
// a class that extends thread that is to be called when program is exiting
static class Message extends Thread {
public void run() {
System.out.println("Bye.");
}
}
public static void main(String[] args) {
try {
// register Message as shutdown hook
Runtime.getRuntime().addShutdownHook(new Message());
// print the state of the program
System.out.println("Program is starting...");
// cause thread to sleep for 3 seconds
System.out.println("Waiting for 3 seconds...");
Thread.sleep(3000);
// print that the program is closing
System.out.println("Program is closing...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Let us compile and run the above program, this will produce the following result −
Program is starting... Waiting for 3 seconds... Program is closing... Bye.