Brief analysis of Java.lang.Runtime class

Source: Internet
Author: User
Tags terminates

I. Overview
The runtime class encapsulates the run-time environment. Each Java application has a runtime class instance that enables the application to connect to the environment in which it is running.
It is generally not possible to instantiate a runtime object, and an application cannot create its own runtime class instance, but can obtain a reference to the current runtime runtime object through the GetRuntime method.
Once you have a reference to the current runtime object, you can call the runtime object's method to control the state and behavior of the Java Virtual machine.
SecurityException exceptions are often caused when applets and other untrusted code call any runtime method.

Second, API preview
Addshutdownhook (Thread Hook)
Register a new virtual machine to close the hook.
Availableprocessors ()
Returns the number of available processors to the Java virtual machine.
EXEC (String command)
Executes the specified string command in a separate process.
EXEC (string[] cmdarray)
Executes the specified commands and variables in a separate process.
EXEC (string[] cmdarray, string[] envp)
Executes the specified command and variable in a separate process for the specified environment.
EXEC (string[] cmdarray, string[] envp, File dir)
Executes the specified commands and variables in a separate process that specifies the environment and working directory.
EXEC (String command, string[] envp)
Executes the specified string command in a separate process in the specified environment.
EXEC (String command, string[] envp, File dir)
Executes the specified string command in a separate process with the specified environment and working directory.
Exit (int status)
Terminates the currently running Java virtual machine by starting the shutdown sequence of the virtual machine.
Freememory ()
Returns the amount of idle memory in a Java virtual machine.
GC ()
Run the garbage collector.
InputStream Getlocalizedinputstream (InputStream in)
is obsolete. Starting with JDK 1.1, the preferred way to convert a local coded byte stream to a Unicode character stream is to use the InputStreamReader and BufferedReader classes.
OutputStream Getlocalizedoutputstream (OutputStream out)
is obsolete. Starting with JDK 1.1, the preferred way to convert a stream of Unicode characters to a local coded byte stream is to use the OutputStreamWriter, BufferedWriter, and PrintWriter classes.
GetRuntime ()

Returns the run-time object associated with the current Java application.
Halt (int status)
Forcibly terminates the currently running Java virtual machine.
Load (String filename)
Loads the specified file name as a dynamic library.
LoadLibrary (String libname)
Loads a dynamic library with the specified library name.
MaxMemory ()
Returns the maximum amount of memory that the Java virtual machine is attempting to use.
Removeshutdownhook (Thread Hook)
Unregister a previously registered virtual institution closed hook.
Runfinalization ()
The terminating method for all objects that are running pending finalization.
Runfinalizersonexit (value)
is obsolete. This method itself has no security. It may invoke the finalization method on the object being used, while other threads are manipulating these objects, resulting in improper behavior or deadlock.
TotalMemory ()
Returns the total amount of memory in the Java virtual machine.
Traceinstructions (ON)
Enable/disable command tracking.
Tracemethodcalls (ON)
Enables/disables method call tracing.

Three, the common application 1, memory management:
Java provides a mechanism for automatic collection of useless units. The TotalMemory () and Freememory () methods allow you to know how large the heap memory of an object is, and how much remains.
Java periodically reclaims garbage objects (unused objects) in order to free up memory space. However, if you want to collect obsolete objects before the next specified period in the collector, you can run the garbage collector as needed by calling the GC () method. A good test method is to call the GC () method first, then call the Freememory () method to see the basic memory usage, then execute the code, and then call the Freememory () method again to see how much memory is allocated. The following program demonstrates this idea. This example comes from the Java core Technology Volume One
classmemorydemo{ Public Static voidMain (String args[]) {Runtime R=Runtime.getruntime (); Longmem1,mem2; Integer someints[]=Newinteger[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(inti=0; i<1000; i++) Someints[i] =NewInteger (i); MEM2=r.freememory (); System.out.println ("Free Memory after allocation:" +mem2); System.out.println ("Memory used by allocation:" + (mem1-mem2)); //Discard Intergers                 for(inti=0; i<1000; i++) Someints[i] =NULL; R.GC (); //Request Garbage CollectionMEM2 =r.freememory (); System.out.println ("Free memory after collecting" + "discarded integers:" +mem2); } }

The results of the compilation run are as follows (the results of different machines running at different times are 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. Perform other procedures
In a secure environment, Java can be used in multitasking operating systems to perform other particularly large processes (that is, programs). The ECEC () method has several forms that name the program you want to run and its input parameters. The ECEC () method returns a Process object that you can use to control the interaction of a Java program with a newly running process. The ECEC () method is essentially dependent on the environment.
The following example uses the ECEC () method to start Notepad Notepad for Windows. This example must be run on the Windows operating system.

This example comes from the Java core Technology Volume One
classExecdemo {
PublicStaticvoidMain (String args[]) {
Runtime r = Runtime.getruntime ();
Process p =NULL;
Try{
p = r.exec ("Notepad");
}Catch(Exception e) {
System.out.println ("Error executing notepad.");
}
}
}there are several other forms of ECEC (), the most common one being demonstrated in the example. After the ECEC () method returns to the process object, the process method can be used after the new program has started running. You can kill a child process with the Destory () method, or you can use the WAITFOR () method to wait for the program to end, and the Exitvalue () method returns the value returned at the end of the child process. If there is no error, 0 is returned, otherwise 0 is not returned. The following is an improved version of the example of the ECEC () method. The example is modified to wait until the running process exits:

This example comes from the Java core Technology Volume One
Class Execdemofini {
public static void Main (String args[]) {
Runtime r = Runtime.getruntime ();
Process p = null;
try{
p = r.exec ("notepad");
P.waitfor ();
} catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Error executing Notepad.");
}
System.out.println ("Notepad returned" + p.exitvalue ());
}
}
The following is the result of the run (when Notepad is closed, the program is run and the information is printed):
Notepad returned 0
Please press any key to continue ...

When a child process is running, you can read and write to the standard input and output. The Getoutputstream () method and the getInputStream () method return the standard input and output of the child process.
four, from the Sun Company's Java.long.Runtime Class API document, the online CHM Chinese version, very easy to find. For convenience, I copied the runtime API documentation from the Sun Company's Javadoc site.

Brief analysis of Java.lang.Runtime class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.