现在的位置: 首页 > 综合 > 正文

java.lang.Runtime

2013年08月06日 ⁄ 综合 ⁄ 共 6532字 ⁄ 字号 评论关闭

package java.lang;

import java.io.*;
import java.util.StringTokenizer;

/**
 *
 * 控制java虚拟机的对象,它是一个单例
 *
 * comment by liqiang
 *
 */

public class Runtime {
 //类初始化时生成唯一的一个实例
    private static Runtime currentRuntime = new Runtime();

    //获得Runtime的唯一实例
    public static Runtime getRuntime() {
 return currentRuntime;
    }

    //私有构造函数
    private Runtime() {}

    /**
     *
     * 终止当前运行的java虚拟机
     *
     * 它会按照终止顺序终止JVM,顺序包括两个部分
     * 1 运行所有注册的关闭钩的线程
     * 2 如果设置状态为关闭时做清除,则所有未清除的对象将调用其finalize方法
     *
     */
    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"));
 }
 
 Shutdown.add(hook);
    }

    /**
     *
     * 注销一个注册钩
     *
     */
    public boolean removeShutdownHook(Thread hook) {
 SecurityManager sm = System.getSecurityManager();
 if (sm != null) {
     sm.checkPermission(new RuntimePermission("shutdownHooks"));
 }
 
 return Shutdown.remove(hook);
    }

    /**
     *
     * 强制停止正在运行的虚拟机
     * 它不会运行关闭钩线程,也不会调用未清除的对象的finalize方法
     *
     */
    public void halt(int status) {
 SecurityManager sm = System.getSecurityManager();
 if (sm != null) {
     sm.checkExit(status);
 }
 
 Shutdown.halt(status);
    }

    /**
     *
     * 在虚拟机退出是调用未清除对象的finalize方法
     * value为true表示调用,false表示不调用
     *
     */
    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);
    }

    /*
     *
     * 执行命令的本地方法
     *
     */
    private native Process execInternal(String cmdarray[], String envp[], String path)
  throws IOException;

    /**
     *
     * 调用系统命令
     * 例如:Runtime.getRuntime().exec("notepad");将启动一个记事本
     *
     */
    public Process exec(String command) throws IOException {
 return exec(command, null);
    }

    /**
     *
     * 调用系统命令
     *
     * @param      cmd  系统的命令行命令
     * @param      envp 表示命令的参数,是name=value值对的形式    
     *
     */
    public Process exec(String cmd, String envp[]) throws IOException {
        return exec(cmd, envp, null);
    }
   
    /**
     *
     * 调用系统命令
     *
     */
    public Process exec(String command, String envp[], File dir)
        throws IOException {
 int count = 0;
 //命令数组
 String cmdarray[];
  StringTokenizer st;

   //命令字符串的长度为0抛出异常
        if (command.length() == 0)
            throw new IllegalArgumentException("Empty command");

    //拆分命令字符串到一个数组中
 st = new StringTokenizer(command);
  count = st.countTokens();
 cmdarray = new String[count];
 //重新生成一个StringTokenizer是没有必要的
 st = new StringTokenizer(command);
 count = 0;
  while (st.hasMoreTokens()) {
   cmdarray[count++] = st.nextToken();
  }
  
  
 return exec(cmdarray, envp, dir);
    }

    /**
     *
     * 调用系统命令
     *
     */
    public Process exec(String cmdarray[]) throws IOException {
 return exec(cmdarray, null);
    }

    /**
     *
     * 调用系统命令
     *
     */
    public Process exec(String cmdarray[], String envp[]) throws IOException {
 return exec(cmdarray, envp, null);
    }

    /**
     *
     * 调用系统命令
     *
     * @param      cmdarray   命令数组                     
     * @param      envp       参数数组
     * @param      dir        子处理的工作路径,如果为null则使用单前的工作路径
     *
     */
    public Process exec(String cmdarray[], String envp[], File dir)
 throws IOException { 
    //拷贝命令数组
 cmdarray = (String[])cmdarray.clone();
 
 //如果参数不为空,则拷贝参数数组
 envp = (envp != null ? (String[])envp.clone() : null);
  //如果参数数组为空数组则抛出异常
        if (cmdarray.length == 0) {
            throw new IndexOutOfBoundsException();           
        }
       
        //检查是否有null命令有则抛出异常
        for (int i = 0; i < cmdarray.length; i++) {
            if (cmdarray[i] == null) {
                throw new NullPointerException();
            }
        }
       
        //如果参数数组不为空,检查参数数组中是否有null项有则抛出异常
        if (envp != null) {
            for (int i = 0; i < envp.length; i++) {
                if (envp[i] == null) {
                    throw new NullPointerException();
                }
            }
        }
       
    //安全检查   
 SecurityManager security = System.getSecurityManager();
 if (security != null) {
     security.checkExec(cmdarray[0]);
 }
 
        String path = (dir == null ? null : dir.getPath());
       
    //执行命令   
 return execInternal(cmdarray, envp, path);
    }

    /**
     *
     * 返回JVM的处理器数,最少为1
     *
     */
    public native int availableProcessors();

    /**
     *
     * 返回可用的内存数
     *
     */
    public native long freeMemory();

    /**
     *
     * 返回JVM占用的内存数
     *
     * Returns the total amount of memory in the Java virtual machine.
     * The value returned by this method may vary over time, depending on
     * the host environment.
     * <p>
     * Note that the amount of memory required to hold an object of any
     * given type may be implementation-dependent.
     *
     * @return  the total amount of memory currently available for current
     *          and future objects, measured in bytes.
     */
    public native long totalMemory();

    /**
     *
     * 返回JVM可用的最大内存数,它的上限与实际物理内存有关,还和
     * 当前操作系统的一个进程可使用的最大内存数有关
     *
     */
    public native long maxMemory();

    /**
     *
     * 做垃圾回收处理
     *
     */
    public native void gc();

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

    /**
     *
     * 运行清空处理
     *
     */
    public void runFinalization() {
 runFinalization0();
    }

    /**
     *
     * 设置是否显示结构轨迹
     *
     */
    public native void traceInstructions(boolean on);

    /**
     *
     * 设置方法调用轨迹
     *
     */
    public native void traceMethodCalls(boolean on);

    /**
     *
     * 装载指定文件名的动态链接库
     * 例子: Runtime.getRuntime().load("/home/avh/lib/libX11.so");
     *
     */
    public void load(String filename) {
        load0(System.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);
    }

    /**
     *
     * 加载动态链接库
     *
     */
    public void loadLibrary(String libname) {
        loadLibrary0(System.getCallerClass(), libname);
    }

    synchronized void loadLibrary0(Class fromClass, String libname) {
    //安全检查
 SecurityManager security = System.getSecurityManager();
 if (security != null) {
     security.checkLink(libname);
 }
 
 //如果存在File.separatorChar字符则抛出异常
 if (libname.indexOf((int)File.separatorChar) != -1) {
     throw new UnsatisfiedLinkError(
    "Directory separator should not appear in library name: " + libname);
 }
 
 ClassLoader.loadLibrary(fromClass, libname, false);
    }

    public InputStream getLocalizedInputStream(InputStream in) {
 return in;
    }

    public OutputStream getLocalizedOutputStream(OutputStream out) {
 return out;
    }

}

抱歉!评论已关闭.