Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

RunTime Class in Java

  • The RunTime class in Java is a part of the Java API that provides an interface to the Java runtime system.It allows system commands to be executed, controls processes, and gives JVM (Java Virtual Machine) information. Developers can interact with the underlying operating system and carry out operations like running external programmes, managing memory, and managing system resources by using the RunTime class.
  • The RunTime class in Java offers a wide range of capabilities that can greatly enhance the functionality and performance of Java applications. Let's dive into some of its key features and how they can be utilized effectively.

1. Executing System Commands

  • The ability to run system commands from within a Java programme is one of the main functions of the RunTime class. With the help of this feature, developers can easily combine Java applications and the underlying operating system. By utilizing the exec() method provided by the RunTime class, developers can execute commands such as creating directories, launching external programs, or even performing complex system operations.

Java code demonstrates how to use the RunTime class to run the system command create new directory.




import java.io.IOException;

public class RuntimeExample {
    public static void main(String[] args) {
        try {
            // Create a new directory using the 'mkdir' command
            Process process = Runtime.getRuntime().exec("mkdir new_directory");

            // Wait for the process to complete
            process.waitFor();

            System.out.println("Directory created successfully!");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output:

Directory created successfully!
 

Developers can easily interact with the operating system and complete a variety of tasks by utilising the power of the RunTime class.




2. Managing Processes

  • Another important feature of the RunTime class is its ability to manage processes. The exec() method returns an instance of the Process class, which represents a subprocess created by the Java application. This allows developers to monitor and control the execution of external programs from within their Java code.

Java code example where we execute a system command to launch an external program and wait for its completion.




import java.io.IOException;

public class RuntimeExample {
    public static void main(String[] args) {
        try {
            // Launch an external program using the 'notepad' command
            Process process = Runtime.getRuntime().exec("notepad");

            // Wait for the process to complete
            process.waitFor();

            System.out.println("External program executed successfully!");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output:

External program executed successfully!
 

In this example, the RunTime class is utilized to execute the "notepad" command, which launches the Notepad application. The waitFor() method ensures that the Java application waits until the external program completes its execution.




3. Retrieving Information about the Java Virtual Machine (JVM)

  • The RunTime class provides methods to retrieve various information about the Java virtual machine (JVM). This includes information on the number of processors, Java version, and total memory made available to the JVM.

Java code snippet demonstrates how to use the RunTime class to retrieve the total memory available to the JVM



public class RuntimeExample {
    public static void main(String[] args) {
        // Get the Java runtime
        Runtime runtime = Runtime.getRuntime();

        // Get the total memory available to the JVM in bytes
        long totalMemory = runtime.totalMemory();

        System.out.println("Total memory: " + totalMemory + " bytes");
    }
}

Output:

 Total memory: [totalMemory value] bytes
 

Developers can learn more about the runtime environment and make wise decisions based on the resources available by utilising the methods provided by the RunTime class.


Methods of Java Runtime class





Method Description
public static Runtime getRuntime() The Runtime class instance is returned by getRuntime().
public void addShutdownHook(Thread hook) A new hook thread is registered by addShutdownHook(Thread hook).
exec(String command) It executes the specified command in a different process.
public int availableProcessors() availableProcessors() function returns the number of available processors.
public long freeMemory() The amount of JVM free memory is returned by freeMemory().
public long totalMemory() Total JVM memory is returned by the function totalMemory().
public void exit(int status) Starts the shutdown sequence for the currently running Java virtual machine.

Example of the freeMemory() and totalMemory() methods of the Java Runtime




public class Main{
    public static void main(String arg[]) {
        //getRuntime()
        Runtime runtime = Runtime.getRuntime();
        System.out.println("Free Memory :" + runtime.freeMemory());
        
        // totalMemory()  
        System.out.println("Total Memory : "+runtime.totalMemory());  
        
        for(int i=0;i<1000;i++){  // Creating 1000 instance
        	new Main();  
        } 
        //freeMemory()
        System.out.println("Free Memory after creating 1000 instance : " + Runtime.getRuntime().freeMemory());
        System.gc(); 
        // The garbage collector is started. 
        //This method's name implies that the Java virtual machine makes 
        //greater efforts to recycle unused objects in order to make the 
        //memory they currently occupy available for quick reuse. 
        System.out.println("Free Memory after Running Garbage Collection : " 
                                                + Runtime.getRuntime().freeMemory());
   }
}

Output:

Free Memory :199312320
Total Memory : 201326592
Free Memory after creating 1000 instance : 199312320
Free Memory after Running Garbage Collection : 7672824 

Java Program to Demonstrate the Runtime class Using the exec() Method




public class Main{
    public static void main(String arg[]){
        // Creating a process and execute MS Word
        try {
			Process process = Runtime.getRuntime().exec("WINWORD"); // it will open ms word
		} catch (Exception  e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        System.out.println("MS Word Open successfully");
    }
}

Output:

MS Word Open successfully 

Java program to demonstrate the Runtime class exit() Method, availableProcessors() Method

public class Main{
    public static void main(String arg[]){
        //availableProcessors() method
        System.out.println("" + Runtime.getRuntime().availableProcessors());
        
        //exit() method
        Runtime.getRuntime().exit(0); 
        System.out.println("Program Running Check");
    }
}



Output:

4 


Frequently Asked Questions (FAQ) - RunTime Class in Java

  • The RunTime class in Java allows developers to interact with the underlying operating system, execute system commands, manage processes, and retrieve information about the Java virtual machine (JVM).
  • Yes, the RunTime class provides the exec() method, which allows the execution of system commands. By utilizing this method, developers can execute complex system operations seamlessly from within their Java applications.
  • The RunTime class returns an instance of the Process class, which represents a subprocess created by the Java application. Developers can use this instance to monitor and control the execution of external programs launched from within their Java code.
  • No, the RunTime class can execute commands on both the local operating system and remote systems. By specifying the appropriate command and target system, developers can execute commands on remote machines as well.
  • Yes, the RunTime class provides methods to retrieve information about the Java virtual machine (JVM) and the underlying system resources. Developers can use these methods to obtain details such as the total memory available to the JVM, the number of processors, and the Java version being used.
  • No, the RunTime class is not thread-safe. If multiple threads need to utilize the RunTime class concurrently, proper synchronization mechanisms should be implemented to avoid conflicts and ensure thread safety.

Java Synchronization Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking in multithreading
Garbage Collection
RunTime Class

Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.