java9系列(四)Process API更新

本文主要研究下JEP 102: Process API Updates

ProcessHandle

/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home/lib/src.zip!/java.base/java/lang/ProcessHandle.java

java9新引入了ProcessHandle

/**
 * ProcessHandle identifies and provides control of native processes. Each
 * individual process can be monitored for liveness, list its children,
 * get information about the process or destroy it.
 * By comparison, {@link java.lang.Process Process} instances were started
 * by the current process and additionally provide access to the process
 * input, output, and error streams.
 * <p>
 * The native process ID is an identification number that the
 * operating system assigns to the process.
 * The range for process id values is dependent on the operating system.
 * For example, an embedded system might use a 16-bit value.
 * Status information about a process is retrieved from the native system
 * and may change asynchronously; processes may be created or terminate
 * spontaneously.
 * The time between when a process terminates and the process id
 * is reused for a new process is unpredictable.
 * Race conditions can exist between checking the status of a process and
 * acting upon it. When using ProcessHandles avoid assumptions
 * about the liveness or identity of the underlying process.
 * <p>
 * Each ProcessHandle identifies and allows control of a process in the native
 * system. ProcessHandles are returned from the factory methods {@link #current()},
 * {@link #of(long)},
 * {@link #children}, {@link #descendants}, {@link #parent()} and
 * {@link #allProcesses()}.
 * <p>
 * The {@link Process} instances created by {@link ProcessBuilder} can be queried
 * for a ProcessHandle that provides information about the Process.
 * ProcessHandle references should not be freely distributed.
 *
 * <p>
 * A {@link java.util.concurrent.CompletableFuture} available from {@link #onExit}
 * can be used to wait for process termination, and possibly trigger dependent
 * actions.
 * <p>
 * The factory methods limit access to ProcessHandles using the
 * SecurityManager checking the {@link RuntimePermission RuntimePermission("manageProcess")}.
 * The ability to control processes is also restricted by the native system,
 * ProcessHandle provides no more access to, or control over, the native process
 * than would be allowed by a native application.
 *
 * @implSpec
 * In the case where ProcessHandles cannot be supported then the factory
 * methods must consistently throw {@link java.lang.UnsupportedOperationException}.
 * The methods of this class throw {@link java.lang.UnsupportedOperationException}
 * if the operating system does not allow access to query or kill a process.
 *
 * <p>
 * The {@code ProcessHandle} static factory methods return instances that are
 * <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>,
 * immutable and thread-safe.
 * Use of identity-sensitive operations (including reference equality
 * ({@code ==}), identity hash code, or synchronization) on these instances of
 * {@code ProcessHandle} may have unpredictable results and should be avoided.
 * Use {@link #equals(Object) equals} or
 * {@link #compareTo(ProcessHandle) compareTo} methods to compare ProcessHandles.
 *
 * @see Process
 * @since 9
 */
public interface ProcessHandle extends Comparable<ProcessHandle> {
//...
}

ProcessHandle提供了对本地进程的控制,可以监控其存活,查找其子进程,查看其信息,甚至销毁它。非常适合耗时较长的进程调用。

实例

查看进程信息

    @Test
    public void testProcessHandle() {
        final ProcessHandle processHandle = ProcessHandle.current();
        final ProcessHandle.Info info = processHandle.info();
        System.out.println("Process info =>");
        System.out.format("PID: %s%n", processHandle.pid());
        info.arguments().ifPresent(args -> System.out.format("Arguments: %s%n", Arrays.toString(args)));
        info.command().ifPresent(command -> System.out.format("Command: %s%n", command));
        info.commandLine()
                .ifPresent(commandLine -> System.out.format("Command line: %s%n", commandLine));
        info.startInstant()
                .ifPresent(startInstant -> System.out.format("Start time: %s%n", startInstant));
        info.totalCpuDuration()
                .ifPresent(cpuDuration -> System.out.format("CPU time: %s%n", cpuDuration));
        info.user().ifPresent(user -> System.out.format("User: %s%n", user));
    }

启动/销毁进程

    @Test
    public void testControlProcess() throws IOException {
        final ProcessBuilder processBuilder = new ProcessBuilder("top")
                .inheritIO();
        ProcessHandle processHandle = processBuilder.start().toHandle();
        final CountDownLatch latch = new CountDownLatch(1);

        processHandle.onExit().whenCompleteAsync((handle, throwable) -> {
            if (throwable == null) {
                System.out.println(handle.pid());
            } else {
                throwable.printStackTrace();
            }
            latch.countDown();
        });
        final Thread shutdownThread = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (final InterruptedException e) {
                e.printStackTrace();
            }
            if (processHandle.supportsNormalTermination()) {
                processHandle.destroy();
            } else {
                processHandle.destroyForcibly();
            }
        });
        shutdownThread.start();
        try {
            shutdownThread.join();
            latch.await();
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    }

小结

java9对process api的最大的更新就是引进了ProcessHandle,可以用来查看进程信息,监控并销毁它。

doc

  • Java 9 新特性概述
  • exploring-java-9 feature9/process
  • java9系列(一)安装及jshell使用
  • java9系列(二)docker运行java9
  • java9系列(三)模块系统精要

本文分享自微信公众号 - 码匠的流水账(geek_luandun)

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2018-03-02

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏儿童编程

一张图理清《梅花易数》梗概

学《易经》的目的不一定是为了卜卦,但是了解卜卦绝对能够让你更好地了解易学。今天用一张思维导图对《梅花易数》的主要内容进行概括,希望能够给学友们提供帮助。

31840
来自专栏儿童编程

《动物魔法学校》儿童学编程Scratch之“外观”部分

导读:本文通过一个案例《动物魔法学校》来学习Scratch语言的“外观”部分。之后通过一系列其他功能的综合运用对作品功能进行了扩展。

19140
来自专栏Ken的杂谈

【系统设置】CentOS 修改机器名

18030
来自专栏儿童编程

我不是算命先生,却对占卜有了疑惑——如何论证“占卜前提”的正确与否

事出有因,我对《周易》感兴趣了很多年。只是觉得特别有趣,断断续续学习了一些皮毛。这几天又偶然接触到了《梅花易数》,觉得很是精彩,将五行八卦天干地支都串联了起来。...

15110
来自专栏haifeiWu与他朋友们的专栏

复杂业务下向Mysql导入30万条数据代码优化的踩坑记录

从毕业到现在第一次接触到超过30万条数据导入MySQL的场景(有点low),就是在顺丰公司接入我司EMM产品时需要将AD中的员工数据导入MySQL中,因此楼主负...

29640
来自专栏儿童编程

声音功能让儿童编程更有创造性

导读:Scratch中声音功能非常强大,除了常规的音效,你甚至可以模拟各种乐器的各个发音、设置节拍、休止……如果你愿意,甚至可以用它创作一个交响乐。我们可以引导...

13740
来自专栏儿童编程

天干地支五行八卦的对应关系

19490
来自专栏FSociety

SQL中GROUP BY用法示例

GROUP BY我们可以先从字面上来理解,GROUP表示分组,BY后面写字段名,就表示根据哪个字段进行分组,如果有用Excel比较多的话,GROUP BY比较类...

5.1K20
来自专栏儿童编程

儿童创造力教育与编程教育的碰撞——MIT雷斯尼克教授最新理论梗概

儿童编程教育已经在我国各一线二线城市疯狂出现,颇有“烂大街”的趋势。我们不禁要问很多很多问题:

22170
来自专栏儿童编程

什么样的人生才是有意义的人生——没有标准的标准答案

【导读】其实我们可以跳出这个小圈圈去更加科客观地看一下这个世界。在夜晚的时候我们仰望天空,浩瀚的宇宙中整个地球只是一粒浮尘,何况地球上一个小小的人类?在漫长的历...

1.8K50

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励