Runtime class in Java


Java Multithreading RuntimeViews 1522

Runtime class in Java

RunTime Class in Java

The Java Runtime class is part of the java.lang.Runtime package and has several built-in methods to interact with the runtime environment of the Java application. Every java application has only 1 instance of the Runtime class. The Runtime class provides various information about the application that is running. We can use the getRuntime() method to obtain the instance of the current Runtime object. Since the Runtime class does not have any constructors, it cannot create its own instance.

Java Runtime class methods

The java.lang.Runtime class has several built-in methods as below:

MethodDescription
Runtime getRuntime()Returns the instance of the current Runtime environment
void addShutdownHook(Thread hook)Registers a new virtual machine shutdown hook
int availableProcessors()Returns the available number of processors in the Java virtual machine
Process exec(String command)Executes the specified string command as a separate process
Process exec(String[] cmdarray)Executes the specified command and array arguments as a separate process
Process exec(String command, String[] envp)Executes the specified string command in the specified environment as a separate process
Process exec(String[] cmdarray, String[] envp)Executes the specified command and argument in the specified environment as a separate process
Process exec(String command, String[] envp, File dir)Executes the string command in a separate process with the specified environment and working directory.
Process exec(String[] cmdarray, String[] envp, File dir)Executes the specified command arguments in a separate process with the specified working directory.
void exit(int status)Terminates the currently executing JVM by initiating shutdown sequence
long freeMemory()Returns the amount of free memory available in JVM
void gc()Runs the garbage collector of the JVM
void halt(int status)Forcefully terminates the currently executing JVM
void load(String filename)Loads the native library specified by the filename
long maxMemory()Returns the maximum amount of memory the JVM will attempt to use
boolean removeShutdownHook(Thread hook)De-registers the registerd hook from the JVM
void runFinalization()Runs the finalization method of any object pending finalization
long totalMemory()Returns the total amount of memory available in the JVM
Version version()Returns the version of the currently running JVM

Example: Retrieve runtime environment information

In the below example, we create an instance of the Runtime class by using the getRuntime() method. Using this instance, we can retrieve various information related to the currently executing java environment like available memory using the freeMemory() method, total memory using the totalMemory() method, number of available processors using the availableProcessors() method and maximum memory that the JVM can use by using the maxMemory() method.

public class RuntimeDemo {

  public static void main(String[] args) {
    Runtime r = Runtime.getRuntime();
    
    System.out.println("Available memory in JVM: " + r.freeMemory());
    System.out.println("Total memory in JVM: " + r.totalMemory());
    System.out.println("Available processors: " + r.availableProcessors());
    System.out.println("Maximum memory: " + r.maxMemory());
    
  }

}
Available memory in JVM: 133169152
Total memory in JVM: 134217728
Available processors: 4
Maximum memory: 2124414976

Example: exec() command – Java Runtime class

The exec() method of the Runtime class executes the specified command. In this example, the exec() method opens the notepad. This method throws IllegalArgumentException when the command is null.

import java.io.IOException;

public class RuntimeDemo {

  public static void main(String[] args) {
    Runtime r = Runtime.getRuntime();
    
    try {
      Process p = r.exec("notepad.exe");
      System.out.println("Launched notepad successfully");
    } catch (IOException e) {
      e.printStackTrace();
    }
    
  }

}
Launched notepad successfully

The below example has 2 arguments in the exec() method. The first parameter is the program that we want to execute and the second argument is the file related to the program that we want to launch. This means we want to open the File.txt file that belongs to the notepad.exe program.

import java.io.IOException;

public class RuntimeDemo {

  public static void main(String[] args) {
    Runtime r = Runtime.getRuntime();
    
    try {
      String[] arrcmd = new String[2];
      arrcmd[0] = "notepad.exe";
      arrcmd[1] = "File.txt";
      Process p = r.exec(arrcmd);
      System.out.println("Launched notepad file successfully");
    } catch (IOException e) {
      e.printStackTrace();
    }
    
  }

}
Launched notepad file successfully

Example: addShutdownHook() method

The addShutdownHook() method registers a new virtual machine hook thread. In the below example, the code waits for 3 seconds and then invokes the run() method.

public class AddHookDemo extends Thread{
  
  public void run() {
    System.out.println("Exit code");
  }

  public static void main(String[] args) throws InterruptedException {
    Runtime r = Runtime.getRuntime();
    r.addShutdownHook(new AddHookDemo());
    
    System.out.println("Wait for 3 seconds");
    Thread.sleep(3000);

  }

}
Wait for 3 seconds
Exit code

Example: removeShutdownHook() method

The removeShutdownHook() method de-registers the previously registered hook thread. Since we are invoking the removeShutdownHook() method, it does not execute the run() method.

public class AddHookDemo extends Thread{
  
  public void run() {
    System.out.println("Exit code");
  }

  public static void main(String[] args) throws InterruptedException {
    Runtime r = Runtime.getRuntime();
    AddHookDemo a = new AddHookDemo();
    r.addShutdownHook(a);
    
    System.out.println("Wait for 3 seconds");
    Thread.sleep(3000);
    
    r.removeShutdownHook(a);

  }

}
Wait for 3 seconds

Example: gc() method

The gc() method invokes the garbage collector to release the unused resources. This will help in efficient memory management.

public class gcDemo {

  public static void main(String[] args) {
    Runtime.getRuntime().gc();
    System.out.println("Running garbage collector");

  }

}
Running garbage collector

Example: load() method

The load() method dynamically loads the specified file. We need to pass the complete file path argument to this method.

public class LoadLibrary {

  public static void main(String[] args) {
    Runtime r = Runtime.getRuntime();
    r.load("C:\\Windows\\System32\\crypt32.dll");
    System.out.println("Loading...");

  }

}
Loading...

Example: halt() method

The halt() method of the Java Runtime class forcefully stops the program execution and is not possible to return to the normal state. From the below example we can see that the statements after the halt command are not executed.

public class HaltDemo{

  public static void main(String[] args) {
    Runtime r = Runtime.getRuntime();
    System.out.println("Executing the code");
    r.halt(0);
    System.out.println("Execution complete");
  }

}
v
Executing the code

Reference

Translate ยป