[java] Runtime类解析

概述

每一个java application都有一个Runtime类的单例,这个实例允许应用程序访问一些程序所运行的环境的接口。此类不能被应用程序实例化。

getRuntime方法

程序当前的runtime实例可以通过getRuntime方法得到,代码如下:

 private static Runtime currentRuntime = new Runtime();

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance
     * methods and must be invoked with respect to the current runtime object.
     *
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() {
        return currentRuntime;
    }

比较有意思的是,这里Runtime类的实例化并没有对线程安全做任何特殊处理,因为它采取了hungry模式实现单例,初始化时静态的currentRuntime就会被创建。意味着虚拟机不管程序员使不使用这个实例,但是它都预先将它初始化了。

exec方法

exec方法的作用是:用指定的环境和工作目录在指定的进程中执行指定的字符串命令,也可以说就是执行一个另外的程序。实现如下:

 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);
    }

command会被一个叫做StringTokenizer的类分解为token。然后调用了另一个exec方法

 public Process exec(String[] cmdarray, String[] envp, File dir)
        throws IOException {
        return new ProcessBuilder(cmdarray)
            .environment(envp)
            .directory(dir)
            .start();
    }

这个exec方法new了一个ProcessBuilder实例,然后再根据传入的命令,和当前的环境以及目录,去执行这个命令,同时,返回了一个Process的实例,我们可以使用这个对象控制Java程序与新运行的进程进行交互。

内存管理方法

Runtime类提供了几个可以访问内存信息的方法,这些方法无一例外都是native方法

freeMemory():该方法返回Java虚拟机中的空闲内存,以字节为单位。

public native long freeMemory();

totalMemory():该方法用于返回Java虚拟机中的内存总量。

public native long totalMemory();

maxMemory():该方法用于返回Java虚拟机试图使用的最大内存量。

public native long maxMemory();

一些有意思的方法

availableProcessors方法

 返回Java虚拟机可用的处理器数量。

 public native int availableProcessors();

gc方法

运行垃圾回收器。调用此方法是建议Java虚拟机去回收未使用的对象,以便使它们当前占用的内存能够快速重用。当控件从方法调用返回时,虚拟机已经尽最大努力回收所有丢弃的对象。注意,并不是强制回收,这与System类里面的gc方法是一样的。

public native void gc();

addShutdownHook方法

 public void addShutdownHook(Thread hook) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new RuntimePermission("shutdownHooks"));
        }
        ApplicationShutdownHooks.add(hook);
    }

在java虚拟机当中注册一个新的shutdown hook, 所谓shutdown就是指的虚拟机关闭的时候。这个方法的意思就是当jvm关闭的时候,会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子,当系统执行完这些钩子后,jvm才会关闭。所以这些钩子可以在jvm关闭的时候进行内存清理、对象销毁等操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值