简体   繁体   中英

java Process.waitfor is a blocking call

I want to be able to kick off an external process from within the JVM and reach on its completion.

I could use the ProcessBuilder to create a Process and then do Process.waitFor() to wait for its completion. However, this a blocking call and simply wastes thread resources.

It would make better sense to do this via an event handler and reactive programming. One would think that the JVM could register some sort of a listener with the OS to listen for process completion events, and relay that back to the program.

Does such a mechanism/ API exist? Any alternatives or libraries that achieve this?

Use the NuProcess library if you only need to support Windows, MacOS X, and Linux. It provides non-blocking access to external processes using a callback model -- including I/O and program termination. Disclosure: I am the author of said library.

Spawn new thread that will wait for process completion:

    final Process process = ...;
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                // thread is interrupted, check process state
            }
            // signal main thread
        }
    }).start();

Or use Executors:

    Future<String> future = Executors.newSingleThreadExecutor().submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            process.waitFor();
            return "OK";
        }
    });

Later allows you to check job status via Future API: future.isDone() , future.cancel() , ...

One would think that the JVM could register some sort of a listener with the OS to listen for process completion events, and relay that back to the program.

Only if all the target operating systems for a java support such a mechanism. Do you have some proof that they do?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM