I. Overview
The Runtime class encapsulates the Runtime environment. Each Java application has a Runtime class instance, enabling the application to be connected to the running environment.
Generally, a Runtime object cannot be instantiated, and applications cannot create their own Runtime class instances. However, you can use the getRuntime method to obtain references to the current Runtime object.
Once you get a reference to the current Runtime object, you can call the method of the Runtime object to control the status and behavior of the Java Virtual Machine.
When the Applet and other Untrusted code call any Runtime method, the SecurityException is often caused.
Ii. API Preview
AddShutdownHook (Thread hook)
Register a new virtual machine to disable the hook.
AvailableProcessors ()
Returns the number of processors available to the Java Virtual Machine.
Exec (String command)
Execute the specified string command in a separate process.
Exec (String [] cmdarray)
Execute the specified command and variable in a separate process.
Exec (String [] cmdarray, String [] envp)
Execute the specified command and variable in the independent process of the specified environment.
Exec (String [] cmdarray, String [] envp, File dir)
Execute specified commands and variables in independent processes in the specified environment and working directory.
Exec (String command, String [] envp)
Execute the specified string command in a separate process of the specified environment.
Exec (String command, String [] envp, File dir)
Execute the specified string command in an independent process in the specified environment and working directory.
Exit (int status)
Terminate the currently running Java Virtual Machine by starting the VM close sequence.
FreeMemory ()
Returns the amount of free memory in the Java Virtual Machine.
Gc ()
Run the garbage collector.
InputStream getLocalizedInputStream (InputStream in)
Expired. From JDK 1.1, the first choice for converting local encoding bytes to Unicode encoding streams is to use the InputStreamReader and BufferedReader classes.
OutputStream getLocalizedOutputStream (OutputStream out)
Expired. Starting from JDK 1.1, the preferred method to convert a Unicode bytes stream to a locally encoded byte stream is to use the OutputStreamWriter, BufferedWriter, and PrintWriter classes.
GetRuntime ()
Returns the runtime objects related to the current Java application.
Halt (int status)
Forcibly terminate the currently running Java virtual machine.
Load (String filename)
Load as the specified file name of the dynamic library.
LoadLibrary (String libname)
Load a dynamic library with the specified database name.
MaxMemory ()
Returns the maximum amount of memory that the Java Virtual Machine is trying to use.
Removeshudownhook (Thread hook)
Cancel registration of a previously registered Virtual Machine to close the hook.
RunFinalization ()
The termination method for running all objects that suspend finalization.
RunFinalizersOnExit (value)
Expired. This method is inherently insecure. It may call the termination method for the object being used, and other threads are operating on these objects, resulting in incorrect behavior or deadlock.
TotalMemory ()
Returns the total memory in the Java Virtual Machine.
TraceInstructions (on)
Enable/disable command tracing.
Tracemethodcils (on)
Enable/disable method call tracing.
Iii. common applications
1. Memory Management:
Java provides an automatic collection mechanism for useless units. The totalMemory () and freeMemory () methods can be used to know the heap memory size of an object and the remaining memory size.
Java periodically recycles junk objects (unused objects) to release memory space. However, to collect discarded objects before the next specified cycle of the collector, you can call the gc () method to run useless unit collectors as needed. A good test method is to call the gc () method first, call the freeMemory () method to view the basic memory usage, execute the code, and then call freemory () again () method To see how much memory is allocated. The following program demonstrates this idea.
// This instance comes from volume 1 of java Core Technology
Class MemoryDemo {
Public static void main (String args []) {
Runtime r = Runtime. getRuntime ();
Long mem1, mem2;
Integer someints [] = new Integer [1000];
System. out. println ("Total memory is:" + r. totalMemory ());
Mem1 = r. freeMemory ();
System. out. println ("Initial free is:" + mem1 );
R. gc ();
Mem1 = r. freeMemory ();
System. out. println ("Free memory after garbage collection:" + mem1 );
// Allocate integers
For (int I = 0; I <1000; I ++) someints [I] = new Integer (I );
Mem2 = r. freeMemory ();
System. out. println ("Free memory after allocation:" + mem2 );
System. out. println ("Memory used by allocation:" + (mem1-mem2 ));
// Discard Intergers
For (int I = 0; I <1000; I ++) someints [I] = null;
R. gc (); // request garbage collection
Mem2 = r. freeMemory ();
System. out. println ("Free memory after collecting" + "discarded integers:" + mem2 );
}
}
The running result after compilation is as follows (the running result of different machines at different times is not necessarily the same ):
Total memory is: 2031616
Initial free is: 1818488
Free memory after garbage collection: 1888808
Free memory after allocation: 1872224
Memory used by allocation: 16584
Free memory after collecting discarded integers: 1888808
2. Execute other programs
In a secure environment, you can use Java in a multitasking operating system to execute other very large processes (that is, programs ). The exec () method can be used to name the program to run and its input parameters. The exec () method returns a Process object, which can be used to control the interaction between Java programs and new processes. In essence, the exec () method depends on the environment.
The following example uses the exec () method to start notepad for windows. This example must be run on a Windows operating system.
// This instance comes from volume 1 of Java Core Technology
Class ExecDemo {
Public static void main (String args []) {
Runtime r = Runtime. getRuntime ();
Process p = null;
Try {
P = r.exe c ("notepad ");
} Catch (Exception e ){
System. out. println ("Error executing notepad .");
}
}
}
Exec () has several other forms, which are the most common ones. After the exec () method returns the Process object, you can use the Process method after the new program starts running. You can use the destory () method to kill a child process, or you can use the waitFor () method to wait for the program until the end of the subroutine, And the exitValue () method returns the value returned when the child process ends. If no error exists, 0 is returned; otherwise, non-0 is returned. The following is an improved version of the exec () method example. The example is modified to wait until the running process exits:
// This instance comes from volume 1 of Java Core Technology
Class ExecDemoFini {
Public static void main (String args []) {
Runtime r = Runtime. getRuntime ();
Process p = null;
Try {
P = r.exe c ("notepad ");
P. waitFor ();
} Catch (Exception e ){
System. out. println ("Error executing notepad .");
}
System. out. println ("Notepad returned" + p. exitValue ());
}
}
The following is the running result (when notepad is closed, the program will be run and the information will be printed ):
Notepad returned 0
Press any key to continue...
When the sub-process is running, you can read and write the standard input and output. The getOutputStream () and getInPutStream () Methods return the standard input and output of sub-processes.