Java.lang.Runtime class in Java

Course Curriculum

Java.lang.Runtime class in Java

Java.lang.Runtime class in Java

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.

Methods of Java Runtime class :

1) public static Runtime getRuntime() : This method returns the instance or Runtime object associated with the current Java application.

// Java program to illustrate getRuntime()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
// get the current runtime assosiated with this process
Runtime run = Runtime.getRuntime();
// print the current free memory for this runtime
System.out.println("" + run.freeMemory());
}
}
Output :

124130416

2) public long freeMemory() : This method returns the amount of free memory in the JVM(Java Virtual Machine)

// Java program to illustrate freeMemory()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
// print the number of free bytes
System.out.println("" + Runtime.getRuntime().freeMemory());
}
}
Output :

124130416

3) public long totalMemory() : This method returns the amount of total memory in the JVM(Java Virtual Machine)

// Java program to illustrate totalMemory()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
// print the number of total bytes
System.out.println("" + Runtime.getRuntime().totalMemory());
}
}
Output :

124780544

4) public Process exec(String command)throws IOException : This method executes given command in a separate process.

Exception :

1)SecurityException : If a security manager exists and its checkExec method doesn’t allow creation of the subprocess

2)IOException : If an I/O error occurs

3)NullPointerException : If command is null

ADVERTISING

4)IllegalArgumentException : If command is empty

// Java program to illustrate Process exec()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
try
{
// create a process and execute google-chrome
Process process = Runtime.getRuntime().exec("google-chrome");
System.out.println("Google Chrome successfully started");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output :

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

5) public void addShutdownHook(Thread hook) : This method registers a new virtual-machine shutdown hook thread.

Exception :

1) IllegalArgumentException : If the specified hook has already been registered, or if it can be determined that the hook is already running or has already been run

2) IllegalStateException :If the virtual machine is already in the process of shutting down

3) SecurityException : If a security manager denies RuntimePermission(“shutdownHooks”)

// Java program to illustrate addShutdownHook()
// method of Runtime class
public class PAI
{
// 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("Program exiting");
}
}
public static void main(String[] args)
{
try
{
// register Message as shutdown hook
Runtime.getRuntime().addShutdownHook(new Message());

// cause thread to sleep for 3 seconds
System.out.println("Waiting for 5 seconds...");
Thread.sleep(5000);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output :

Waiting for 5 seconds...
Program exiting

6) public boolean removeShutdownHook(Thread hook) : This method de-registers a previously-registered virtual-machine shutdown hook.

// Java program to illustrate removeShutdownHook()
// method of Runtime class
public class PAI
{
// 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("Program exiting");
}
}
public static void main(String[] args)
{
try
{
Message p = new Message();
// register Message as shutdown hook
Runtime.getRuntime().addShutdownHook(p);

// cause thread to sleep for 3 seconds
System.out.println("Waiting for 5 seconds...");
Thread.sleep(5000);

// remove the hook
Runtime.getRuntime().removeShutdownHook(p);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output :

Waiting for 5 seconds...

7) public int availableProcessors() : This method returns the number of processors available to the JVM (Java virtual machine).

// Java program to illustrate availableProcessors()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
// check the number of processors available
System.out.println("" + Runtime.getRuntime()
.availableProcessors());

}
}
Output :

4

8) public void exit(int status) : This method terminates the currently running Java virtual machine by initiating its shutdown sequence.

// Java program to illustrate exit()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
// cause the program to exit
Runtime.getRuntime().exit(0);

//Nothing will run now.
System.out.println("Program Running Check");
}
}
Output :

No Output

9) public void traceInstructions(boolean a) : This method enables or disables tracing of instructions. If the boolean argument is true then it will suggests that the JVM (Java virtual machine) emits debugging information for each instruction in the virtual machine as it is executed.

// Java program to illustrate traceInstructions()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
// start tracing for instructions
Runtime.getRuntime().traceInstructions(true);

System.out.println("Enabled");
Runtime.getRuntime().traceInstructions(false);
System.out.println("Disabled");

}
}
Output :

Enabled
Disabled

10) public void traceMethodCalls(boolean a) : This method enables or disables tracing of method calls. If the boolean argument is truethen it will suggests that the Java virtual machine emit debugging information for each method in the virtual machine as it is called.

// Java program to illustrate traceMethodCalls()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
// start tracing for instructions
System.out.println("Enabling..");

Runtime.getRuntime().traceMethodCalls(true);
System.out.println("Enabled");
}
}
Output :

Enabling..
Enabled

11) public void loadLibrary(String libname) : This method 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.

Exception :

1) UnsatisfiedLinkError : if the library does not exist.

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

// Java program to illustrate loadLibrary()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
// load a library that is home/saket/Desktop folder
Runtime.getRuntime().loadLibrary("/home/saket/Desktop/Library");

System.out.println("Library Loaded Successfully");
}
}
Output :

Library Loaded Successfully

12) public void load(String filename) : This method Loads the specified filename as a dynamic library. The filename argument must be a complete path name.

Exception :

1) UnsatisfiedLinkError : if the library does not exist.

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

// Java program to illustrate load()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
// load a library that is home/saket/Desktop folder
Runtime.getRuntime().loadLibrary("/home/saket/Desktop/File");

System.out.println("Library Loaded Successfully");
}
}
Output :

Library Loaded Successfully

13) public void gc() : This method runs the garbage collector. Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse.

// Java program to illustrate gc()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
// run the garbage collector
Runtime.getRuntime().gc();

System.out.println("Running");
}
}
Output :

Running

14) public void runFinalization() : This method runs the finalization methods of any objects pending finalization. It suggests that HVM (Java virtual machine) expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run.

// Java program to illustrate runFinalization()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
// run the finalization
Runtime.getRuntime().runFinalization();

System.out.println("Finalized");
}
}
Output :

Finalized

15) public long maxMemory() : This method 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.

// Java program to illustrate maxMemory()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
// print the maximum memory
System.out.println("" + Runtime.getRuntime().maxMemory());
}
}
Output :

922746880

16) public void halt(int status) : This method forcibly terminates the currently running Java virtual machine. This method never returns normally. This method should be used with extreme caution.

Exception :

SecurityException : If a security manager is present and its checkExit method does not permit an exit with the specified status

// Java program to illustrate halt()
// method of Runtime class
public class PAI
{
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 :

No Output

17) public Process exec(String[] cmd) : This method executes the specified command and arguments in a separate process. This is a convenience method.

Exception :

1) IndexOutOfBoundsException : If cmd is an empty array (has length 0)

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

4) IOException : If an I/O error occurs

// Java program to illustrate exec()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
try
{
String[] cmd = new String[2];
cmd[0] = "atom";
cmd[1] = "File.java";
// create a process and execute cmdArray
Process process = Runtime.getRuntime().exec(cmd);

// print another message
System.out.println("File.java opening in atom");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output :

File.java opening in atom

18) public Process exec(String command, String[] envp, File dir) : This method Executes the specified string command in a separate process with the specified environment and working directory. This is a convenience method.

Exception :

1) IndexOutOfBoundsException : If cmd is an empty array (has length 0)

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

4) IOException : If an I/O error occurs

// Java program to illustrate exec()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
try
{
// create a file with the working directory we wish
File f = new File("/home/saket/Desktop");

// create a process and execute gedit and currect environment
Process process = Runtime.getRuntime().exec("gedit", null, f);
System.out.println("Gedit opening.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output :

Gedit opening.

19) public Process exec(String command, String[] envp) : This method executes the specified string command in a separate process with the specified environment. This is a convenience method and behaves in exactly the same way as the invocation exec(command, envp, null).
Exception :

1) IndexOutOfBoundsException : If cmd is an empty array (has length 0)

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

4) IOException : If an I/O error occurs

// Java program to illustrate exec()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
try
{
// create a file with the working directory we wish
File f = new File("/home/saket/Desktop");

// create a process and execute gedit and currect environment
Process process = Runtime.getRuntime().exec("gedit", null);
System.out.println("Gedit opening.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output :

Gedit opening.

20) public Process exec(String[] cmdarray, String[] envp, File dir) : This method executes the specified command and arguments in a separate process with the specified environment and working directory. Given an array of strings cmdarray, representing the tokens of a command line, and an array of strings envp, representing “environment” variable settings, this method creates a new process in which to execute the specified command.
Exception :

1) IndexOutOfBoundsException : If cmd is an empty array (has length 0)

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

4) IOException : If an I/O error occurs

// Java program to illustrate exec()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
try
{
String[] cmd = new String[2];
cmd[0] = "atom";
cmd[1] = "File.java";
// create a file with the working directory we wish
File dir = new File("/home/saket/Desktop");
// create a process and execute cmdArray
Process process = Runtime.getRuntime().exec(cmd, null, dir);
System.out.println("File.java opening.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output :

File.java opening.

21) public Process exec(String[] cmdarray, String[] envp) : This method executes the specified command and arguments in a separate process with the specified environment. This is a convenience method. An invocation of the form exec(cmdarray, envp) behaves in exactly the same way as the invocation exec(cmdarray, envp, null).

Exception :

1) IndexOutOfBoundsException : If cmd is an empty array (has length 0)

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

4) IOException : If an I/O error occurs

// Java program to illustrate exec()
// method of Runtime class
public class PAI
{
public static void main(String[] args)
{
try
{
String[] cmd = new String[2];
cmd[0] = "atom";
cmd[1] = "File.java";
// create a file with the working directory we wish
File dir = new File("/home/saket/Desktop");
// create a process and execute cmdArray
Process process = Runtime.getRuntime().exec(cmd, null);
System.out.println("File.java opening.");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output :

File.java opening.

(Next Lesson) How to start learning Java