Open In App

Java.lang.Runtime class in Java

Last Updated : 06 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Java, the Runtime class is used to interact with Every Java application that 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.

Methods of Java Runtime class

Method  Action Performed
addShutdownHook(Thread hook) Registers a new virtual-machine shutdown hook thread.
availableProcessors() Returns the number of processors available to the JVM (Java virtual machine)
exec(String command) Executes the given command in a separate process
exec(String[] cmd) Executes the specified command and arguments in a separate process.
exec(String command, String[] envp, File dir) Executes the specified string command in a separate process with the specified environment and working directory. 
exec(String command, String[] envp) Executes the specified string command in a separate process with the specified environment.
exec(String[] cmdarray, String[] envp, File dir)  Executes the specified command and arguments in a separate process with the specified environment and working directory.
exec(String[] cmdarray, String[] envp) Executes the specified command and arguments in a separate process with the specified environment. 
exit(int status) Terminates the currently running Java virtual machine by initiating its shutdown sequence.
freeMemory() Returns the amount of free memory in the JVM(Java Virtual Machine)
gc() Runs the garbage collector. Calling this method suggests that the Java virtual machine expands effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse.
getRuntime() Returns the instance or Runtime object associated with the current Java application
halt(int status) Forcibly terminates the currently running Java virtual machine. This method never returns normally. This method should be used with extreme caution.
load(String filename) Loads the specified filename as a dynamic library. The filename argument must be a complete pathname.
loadLibrary(String libname) Loads the dynamic library with the specified library name. A file containing code is loaded from the local system from a place where library files are conventionally obtained.
maxMemory() Returns the maximum amount of memory that the Java virtual machine will attempt to use. If there is no inherent limit then the value Long.MAX_VALUE will be returned
removeShutdownHook(Thread hook) De-registers a previously-registered virtual machine shutdown hook.
runFinalization() Runs the finalization methods of any objects pending finalization. It suggests that JVM (Java virtual machine) expands effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run.
totalMemory() Returns the amount of total memory in the JVM(Java Virtual Machine) 
traceInstructions(boolean a) Enables or disables tracing of instructions. If the boolean argument is true then it will suggest that the JVM emits debugging information for each instruction in the virtual machine as it is executed.
traceMethodCalls(boolean a) Enables or disables tracing of method calls. If the boolean argument is true then it will suggest that the Java virtual machine emits debugging information for each method in the virtual machine as it is called.

Example 1:

Java




// Java Program to Illustrate Runtime class
// Via getRuntime(), freeMemory() and
// totalMemory() Method
 
// Importing required classes
import java.lang.*;
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Method 1: getRuntime()
        // Getting the current runtime associated
        // with this process
        Runtime run = Runtime.getRuntime();
 
        // Printing the current free memory for this runtime
        // using freeMemory() method
        System.out.println("" + run.freeMemory());
 
        // Method 2: freeMemory()
        // Printing the number of free bytes
        System.out.println(
            "" + Runtime.getRuntime().freeMemory());
 
        // Method 3: totalMemory()
        // Printing the number of total bytes
        System.out.println(
            "" + Runtime.getRuntime().totalMemory());
    }
}


Output

132579840
132285936
134217728

Example 2:

Java




// Java Program to Illustrate Runtime class
// Via exec() Method
 
// Importing required classes
import java.util.*;
import java.lang.*;
 
// Main class
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Try block to check for exceptions
        try {
           
            // Creating a process and execute google-chrome
            Process process = Runtime.getRuntime().exec(
                "google-chrome");
            System.out.println(
                "Google Chrome successfully started");
        }
 
        // Catch block to handle the exceptions
        catch (Exception e) {
            // Display the exception on the console
            e.printStackTrace();
        }
    }
}


Output: 

Google Chrome successfully started

Note: Replace with any software you want to start. Here we work on Linux and google-chrome is written like this way only. May differ in windows/mac.

Example 3:

Java




// Java Program to Illustrate Runtime class
// Via availableProcessors() Method, exit() Method
 
// Importing required classes
import java.util.*;
import java.lang.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args) {
 
        // Method 1: availableProcessors()
        // Check the number of processors available
        // and printing alongside
        System.out.println("" + Runtime.getRuntime()
                           .availableProcessors());
 
 
        // Method 2: exit()
        // Making program to exit
        Runtime.getRuntime().exit(0);
 
        // Nothing will run now
        System.out.println("Program Running Check");
 
        // Note: here we will notice that there will be no
        // output generated on console
 
    }
}


Output

4

From the above output, it is made clear that exit() method does not let below print statement to execute as “Program Running Check” is not printed on the console. It can be made clear if we comment out the working of availableProcessors() than exit() method output is as follows: 

Example 4:

Java




// Java Program to illustrate Runtime Class
// Via loadLibrary(), runFinalization()
// gc(), maxMemory()
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Method 1: loadLibrary()
        // Loading a library that is home/saket/Desktop
        // folder
        Runtime.getRuntime().loadLibrary(
            "/home/saket/Desktop/Library");
 
        System.out.println("Library Loaded Successfully");
 
        // Method 2: runFinalization()
        // Run the finalization
        Runtime.getRuntime().runFinalization();
 
        // Print statement
        System.out.println("Finalized");
 
        // Method 3: gc()
        // Run the garbage collector
        Runtime.getRuntime().gc();
 
        System.out.println("Running");
 
        // Method 4: maxMemory()
 
        // Printing  the maximum memory
        System.out.println(
            "" + Runtime.getRuntime().maxMemory());
    }
}


Output: 

Library Loaded Successfully
Finalized
Running
2147483648

Example 5:

Java




// Java program to illustrate halt()
// method of Runtime class
public class GFG
{
    public static void main(String[] args)
    {
        // halt this process
        Runtime.getRuntime().halt(0);
 
        // print a string, just to see if it process is halted
        System.out.println("Process is still running.");
    }
}


Output: 

 

 

From above output it is made clear above program compiled  successfully and run. There is no print statement is execute as we have used halt() method which terminates the further execution of operations.

Example 6:

Java




// Java Program to Illustrate exec()
// Method of Runtime class
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args) {
 
        // Try block to check for exceptions
        try {
 
            // Declaring a string array
            String[] cmd = new String[2];
 
            // Initializing elements of string array
            cmd[0] = "atom";
            cmd[1] = "File.java";
 
            // Creating a file with directory from local systems
            File dir = new File("/Users/mayanksolanki/Desktop");
 
            // Creating a process by creating Process class object
            // and execute above array using exec() method
            Process process = Runtime.getRuntime().exec(cmd, null);
 
            // Display message on console for successful execution
            System.out.println("File.java opening.");
        }
 
        // Catch block to handle exceptions
        catch (Exception e) {
 
            // Display exceptions with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
    }
}


Output: 

File.java opening.



Previous Article
Next Article

Similar Reads

Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
java.lang.reflect.Proxy Class in Java
A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements SerializableFields: protected InvocationHandler hIt han
4 min read
java.lang.MethodType Class in Java
MethodType is a Class that belongs to java.lang package. This class consists of various types of methods that help in most of cases to find the method type based on the input object, or parameters of the method. All the instances of methodType are immutable. This means the objects of the methodType class cannot be overridden by any other objects da
4 min read
java.lang.ref.WeakReference Class In Java
When we create an object in Java, an object isn't weak by default. To create a Weak Reference Object, we must explicitly specify this to the JVM. Why Weak Reference Objects are used: Unlike C/C++, Java supports Dynamic Garbage Collection. This is performed when the JVM runs the Garbage Collector. In order to not waste space, the garbage collector d
3 min read
java.lang.reflect.Parameter Class in Java
java.lang.reflect.Parameter class provides Information about method parameters, including their name and modifiers. It also provides an alternate means of obtaining attributes for the parameter. Some useful methods of Parameter class are: public int getModifiers(): It returns the modifier flags for the parameter represented by this Parameter object
4 min read
java.lang.ref.SoftReference Class in Java
When we create an object in Java, an object isn't soft by default. To create a Soft Reference Object, we must explicitly specify this to the JVM. In Soft reference, even if the object is free for garbage collection then also it's not garbage collected until JVM is in need of memory badly. The objects get cleared from the memory when JVM runs out of
3 min read
java.lang.reflect.Constructor Class in Java
java.lang.reflect.Constructor class is used to manage the constructor metadata like the name of the constructors, parameter types of constructors, and access modifiers of the constructors. We can inspect the constructors of classes and instantiate objects at runtime. The Constructor[] array will have one Constructor instance for each public constru
4 min read
java.lang.ref.ReferenceQueue Class in Java
A ReferenceQueue is a simple data structure onto which the garbage collector places reference objects when the reference field is cleared (set to null). You would use a reference queue to find out when an object becomes softly, weakly, or phantom reachable, so your program can take some action based on that knowledge. For example, a program might p
3 min read
java.lang.reflect.Method Class in Java
java.lang.reflect.Method class provides necessary details about one method on a certain category or interface and provides access for the same. The reflected method could also be a category method or an instance method (including an abstract method). This class allows broadening of conversions to occur when matching the actual parameters to call th
3 min read
java.lang.reflect.ReflectPermission Class in Java
ReflectPermission class extends BasicPermission class. It is a “named” permission i.e it contains a name but no action. It may implement actions on top of BasicPermission, if desired. It is used to get information about the behaviour of Constructors. ConstructorsDescriptionReflectPermission(String name)It is used to create a ReflectPermission with
2 min read
java.lang.reflect.Modifier Class in Java
The java.lang.reflect.Modifier class contains methods used to get information about class, member and method access modifiers. The modifiers are represented as int value with set bits at distinct positions. The int value represents different modifiers. These values are taken from the tables in sections 4.1, 4.4, 4.5, and 4.7 of The JVM Specificatio
7 min read
java.lang.reflect.Field Class in Java
The ability of the software to analyze itself is known as Reflection. This is provided by the java.lang.reflect package and elements in Class .Field serves the same purpose as the whole reflection mechanism, analyze a software component and describe its capabilities dynamically, at run time rather than at compile time .Java, like many other languag
5 min read
java.lang.management.ThreadInfo Class in Java
java.lang.management.ThreadInfo class contains methods to get information about a thread. This information includes: Thread IDThread NameState of the ThreadStack trace of the ThreadThe object upon which the Thread is blockedList of object monitors that are blocked by the ThreadList of ownable synchronizers blocked by the ThreadNumber of times the T
4 min read
java.lang.management.ManagementPermission Class in Java
java.lang.ManagementPermission Class contains abstract methods to determine access to a system resource. Every object has some name. Most permission object also has some "actions" associated with it that tells which activities are permitted by this permission object. Class declaration : public final class ManagementPermission extends BasicPermissio
3 min read
java.lang.ref.PhantomReference Class in Java
When we create an object in Java, an object is strong by default. To create a Phantom Reference Object, we must explicitly specify this to the JVM. Phantom Reference Objects are created as phantom reference object is eligible for garbage collection, but it is not collected instantly. Instead, it is pushed into a ReferenceQueue so that all such enqu
4 min read
java.lang.ref.Reference Class in Java
java.lang.ref.Reference Class is an abstract base class for reference object. This class contains methods used to get information about the reference objects. This class is not a direct subclass because the operations on the reference objects are in close co-operation with the garbage collector. Class declaration: prevent public abstract class Refe
3 min read
Java.lang.Number Class in Java
Most of the time, while working with numbers in java, we use primitive data types. But, Java also provides various numeric wrapper sub classes under the abstract class Number present in java.lang package. There are mainly six sub-classes under Number class.These sub-classes define some useful methods which are used frequently while dealing with num
9 min read
Java.lang.Boolean Class in Java
Java provides a wrapper class Boolean in java.lang package. The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field, whose type is boolean. In addition, this class provides useful methods like to convert a boolean to a String and a String to a boolean, while dealing with a boolea
8 min read
Java.Lang.Double Class in Java
Double class is a wrapper class for the primitive type double which contains several methods to effectively deal with a double value like converting it to a string representation, and vice-versa. An object of the Double class can hold a single double value. Double class is a wrapper class for the primitive type double which contains several methods
4 min read
Java.Lang.Byte class in Java
In Java, Byte class is a wrapper class for the primitive type byte which contains several methods to effectively deal with a byte value like converting it to a string representation, and vice-versa. An object of the Byte class can hold a single byte value. Constructors of Byte Class There are mainly two constructors to initialize a Byte object- 1.
6 min read
Java.Lang.Long class in Java
Long class is a wrapper class for the primitive type long which contains several methods to effectively deal with a long value like converting it to a string representation, and vice-versa. An object of Long class can hold a single long value. There are mainly two constructors to initialize a Long object- Long(long b): Creates a Long object initial
12 min read
Java.lang.Enum Class in Java
Enum class is present in java.lang package. It is the common base class of all Java language enumeration types. For information about enums, refer enum in java Class Declaration public abstract class Enum<E extends Enum> extends Object implements Comparable, Serializable As we can see, that Enum is an abstract class, so we can not create obje
8 min read
Java.lang.Character.Subset Class in Java
Character.Subset Class represents particular subsets of the Unicode(standards using hexadecimal values to express characters - 16bit) character set. The subset, it defines in Character set is UnicodeBlock. Declaration : public static class Character.Subset extends Object Constructors : protected Character.Subset(String str) : Constructs new subset
2 min read
Java.lang.Math Class in Java | Set 2
Java.lang.Math Class in Java | Set 1 More Methods: cosh() : java.lang.Math.cosh() method returns the hyperbolic cosine of the argument passed. Special cases : Result is NaN, if argument is NaN. Result is 1.0, if the argument is zero. Result is +ve infinity, if argument is infinite. Syntax: public static double cosh(double arg) Parameters: arg - The
6 min read
Java.lang.Character.UnicodeBlock Class in Java
Character.UnicodeBlock Class represents particular Character blocks of the Unicode(standards using hexadecimal values to express characters - 16 bit) specifications. Character Blocks define characters used for specific purpose. Declaration : public static final class Character.UnicodeBlock extends Character.Subset Methods of Character.UnicodeBlock
2 min read
Java.lang.Void Class in Java
Java.lang.Void class is a placeholder that holds a reference to a class object if it represents a void keyword. It is an uninstantiable placeholder. Well, uninstantiable means that this class has a private constructor and no other constructor that we can access from outside. Methods of lang.void class is all inherited from Object class in Java: get
1 min read
Java.lang.Process class in Java
The abstract Process class is a process that is, an executing program. Methods provided by the Process are used to perform input, and output, waiting for the process to complete, checking the exit status of the process, and destroying the process. It extends class Object.It is used primarily as a superclass for the type of object created by exec()
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg