您的位置:首页 > 编程语言 > Java开发

java Runtime 解析

2016-03-24 16:47 399 查看

源码

package java.lang;

import java.io.*;
import java.util.StringTokenizer;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;

public class Runtime {
private static Runtime currentRuntime = new Runtime();

/**
* 返回与当前应用程序相关的java运行时对象。
* 大多数类的方法都是类的,例如,运行时的方法和必须在当前运行时对象调用。
*/
public static Runtime getRuntime() {
return currentRuntime;
}

/** 返回与当前应用程序相关的java运行时对象,不支持人为创建的Runtime */
private Runtime() {}

/**
* 通过启动虚拟机的关闭序列,终止当前正在运行的 Java 虚拟机。此方法从不正常返回。可以将变量作为一个状态码;根据惯例,非零的状态码表示非正常终止。
* 虚拟机的关闭序列包含两个阶段。在第一个阶段中,会以某种未指定的顺序启动所有已注册的关闭钩子(hook)(如果有的话),并且允许它们同时运行直至结束。
* 在第二个阶段中,如果已启用退出终结,则运行所有未调用的终结方法。一旦完成这个阶段,虚拟机就会暂停。
* 如果在虚拟机已开始其关闭序列后才调用此方法,那么若正在运行关闭钩子,则将无限期地阻断此方法。
* 如果已经运行完关闭钩子,并且已启用退出终结 (on-exitfinalization),那么此方法将利用给定的状态码(如果状态码是非零值)暂停虚拟机;否则将无限期地阻断虚拟机。
*
*/
public void exit(int status) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkExit(status);
}
Shutdown.exit(status);
}

/**
*注册新的虚拟机来关闭钩子。
*/
public void addShutdownHook(Thread hook) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("shutdownHooks"));
}
ApplicationShutdownHooks.add(hook);
}

/**
* 取消注册某个先前已注册的虚拟机关闭钩子。
* 如果指定的钩子先前已注册并且成功地取消注册,则返回 true,其他情况返回 false。
*/
public boolean removeShutdownHook(Thread hook) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("shutdownHooks"));
}
return ApplicationShutdownHooks.remove(hook);
}

/**
* 强行终止目前正在运行的 Java 虚拟机。此方法从不正常返回。
* 应小心使用此方法。与 exit方法不同,此方法不会启动关闭钩子,并且如果已启用退出终结,此方法也不会运行未调用的终结方法。
* 如果已经发起关闭序列,那么此方法不会等待所有正在运行的关闭钩子或终结方法完成其工作。
*/
public void halt(int status) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkExit(status);
}
Shutdown.halt(status);
}

/**
* Enable or disable finalization on exit; doing so specifies that the
* finalizers of all objects that have finalizers that have not yet been
* automatically invoked are to be run before the Java runtime exits.
* By default, finalization on exit is disabled.
*
* <p>If there is a security manager,
* its <code>checkExit</code> method is first called
* with 0 as its argument to ensure the exit is allowed.
* This could result in a SecurityException.
*
* @param value true to enable finalization on exit, false to disable
* @deprecated  This method is inherently unsafe.  It may result in
*      finalizers being called on live objects while other threads are
*      concurrently manipulating those objects, resulting in erratic
*      behavior or deadlock.
*
* @throws  SecurityException
*        if a security manager exists and its <code>checkExit</code>
*        method doesn't allow the exit.
*
* @see     java.lang.Runtime#exit(int)
* @see     java.lang.Runtime#gc()
* @see     java.lang.SecurityManager#checkExit(int)
* @since   JDK1.1
*/
@Deprecated
public static void runFinalizersOnExit(boolean value) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
try {
security.checkExit(0);
} catch (SecurityException e) {
throw new SecurityException("runFinalizersOnExit");
}
}
Shutdown.setRunFinalizersOnExit(value);
}

/**
* Executes the specified string command in a separate process.
*/
public Process exec(String command) throws IOException {
return exec(command, null, null);
}

/**
* Executes the specified string command in a separate process with the specified environment.
*
*/
public Process exec(String command, String[] envp) throws IOException {
return exec(command, envp, null);
}

/**
* Executes the specified string command in a separate process with the specified environment and working directory.
*
*/
public Process exec(String command, String[] envp, File dir)
throws IOException {
if (command.length() == 0)
throw new IllegalArgumentException("Empty command");

StringTokenizer st = new StringTokenizer(command);
String[] cmdarray = new String[st.countTokens()];
for (int i = 0; st.hasMoreTokens(); i++)
cmdarray[i] = st.nextToken();
return exec(cmdarray, envp, dir);
}

/**
* Executes the specified command and arguments in a separate process.
*
*/
public Process exec(String cmdarray[]) throws IOException {
return exec(cmdarray, null, null);
}

/**
* Executes the specified command and arguments in a separate process with the specified environment.
*
*/
public Process exec(String[] cmdarray, String[] envp) throws IOException {
return exec(cmdarray, envp, null);
}

/**
* Executes the specified command and arguments in a separate process with
* the specified environment and working directory.
*
*/
public Process exec(String[] cmdarray, String[] envp, File dir)
throws IOException {
return new ProcessBuilder(cmdarray)
.environment(envp)
.directory(dir)
.start();
}

/**
* 向 Java 虚拟机返回可用处理器的数目。
* 该值在特定的虚拟机调用期间可能发生更改。因此,对可用处理器数目很敏感的应用程序应该不定期地轮询该属性,并相应地调整其资源用法。
* 虚拟机可用的最大处理器数目;从不小于 1
*/
public native int availableProcessors();

/**
* 返回 Java 虚拟机中的空闲内存量。调用 gc 方法可能导致 freeMemory 返回值的增加。
*/
public native long freeMemory();

/**
* 返回 Java 虚拟机中的内存总量。此方法返回的值可能随时间的推移而变化,这取决于主机环境。
*/
public native long totalMemory();

/**
* 返回 Java 虚拟机试图使用的最大内存量。如果内存本身没有限制,则返回值 Long.MAX_VALUE。
*/
public native long maxMemory();

/**
* 运行垃圾回收器。调用此方法意味着 Java 虚拟机做了一些努力来回收未用对象,以便能够快速地重用这些对象当前占用的内存。
* 当控制从方法调用中返回时,虚拟机已经尽最大努力回收了所有丢弃的对象。
*
* 垃圾回收机制主要有两类:引用计数收集器  跟踪收集器
*/
public native void gc();

/* Wormhole for calling java.lang.ref.Finalizer.runFinalization */
private static native void runFinalization0();

/**
* 运行挂起 finalization 的所有对象的终止方法。
* 调用此方法意味着 Java 虚拟机做了一些努力运行已被丢弃对象的 finalize 方法,
* 但是这些对象的 finalize 方法还没有运行。当控制从方法调用中返回时,Java 虚拟机已经尽最大努力去完成所有未执行的终止方法。
* 如果不显式调用 runFinalization 方法,则 Java 虚拟机会根据需要在单独的线程中自动执行此终止过程。
*/
public void runFinalization() {
runFinalization0();
}

/**
* 启用/禁用指令跟踪。
*/
public native void traceInstructions(boolean on);

/**
* 启用/禁用方法调用跟踪。
*/
public native void traceMethodCalls(boolean on);

/**
* 加载具有指定动态库。
*/
@CallerSensitive
public void load(String filename) {
load0(Reflection.getCallerClass(), filename);
}

synchronized void load0(Class fromClass, String filename) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkLink(filename);
}
if (!(new File(filename).isAbsolute())) {
throw new UnsatisfiedLinkError(
"Expecting an absolute path of the library: " + filename);
}
ClassLoader.loadLibrary(fromClass, filename, true);
}

/**
* 加载具有指定动态库。
*/
@CallerSensitive
public void loadLibrary(String libname) {
loadLibrary0(Reflection.getCallerClass(), libname);
}

synchronized void loadLibrary0(Class fromClass, String libname) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkLink(libname);
}
if (libname.indexOf((int)File.separatorChar) != -1) {
throw new UnsatisfiedLinkError(
"Directory separator should not appear in library name: " + libname);
}
ClassLoader.loadLibrary(fromClass, libname, false);
}

/**
* Creates a localized version of an input stream. This method takes
* an <code>InputStream</code> and returns an <code>InputStream</code>
* equivalent to the argument in all respects except that it is
* localized: as characters in the local character set are read from
* the stream, they are automatically converted from the local
* character set to Unicode.
* <p>
* If the argument is already a localized stream, it may be returned
* as the result.
*
* @param      in InputStream to localize
* @return     a localized input stream
* @see        java.io.InputStream
* @see        java.io.BufferedReader#BufferedReader(java.io.Reader)
* @see        java.io.InputStreamReader#InputStreamReader(java.io.InputStream)
* @deprecated As of JDK 1.1, the preferred way to translate a byte
* stream in the local encoding into a character stream in Unicode is via
* the <code>InputStreamReader</code> and <code>BufferedReader</code>
* classes.
*/
@Deprecated
public InputStream getLocalizedInputStream(InputStream in) {
return in;
}

/**
* Creates a localized version of an output stream. This method
* takes an <code>OutputStream</code> and returns an
* <code>OutputStream</code> equivalent to the argument in all respects
* except that it is localized: as Unicode characters are written to
* the stream, they are automatically converted to the local
* character set.
* <p>
* If the argument is already a localized stream, it may be returned
* as the result.
*
* @deprecated As of JDK 1.1, the preferred way to translate a
* Unicode character stream into a byte stream in the local encoding is via
* the <code>OutputStreamWriter</code>, <code>BufferedWriter</code>, and
* <code>PrintWriter</code> classes.
*
* @param      out OutputStream to localize
* @return     a localized output stream
* @see        java.io.OutputStream
* @see        java.io.BufferedWriter#BufferedWriter(java.io.Writer)
* @see        java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
* @see        java.io.PrintWriter#PrintWriter(java.io.OutputStream)
*/
@Deprecated
public OutputStream getLocalizedOutputStream(OutputStream out) {
return out;
}

}


该类用于管理类运行期间的各种信息

1.虚拟机的退出.关闭(Shutdown)/运行内存(memory)和处理器(processor)信息

2.虚拟机关闭Hook的增加/移除/运行

3.基于process的cmd命令的exec (ProcessBuilder)

4.方法和指令的启用/禁用跟踪 (ApplicationShutdownHooks)

5.动态库的加载 (load/loadLibrary)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: