How to add a timeout value when using Java's Runtime.exec()?

前端 未结 17 1791
长发绾君心
长发绾君心 2020-11-27 12:08

I have a method I am using to execute a command on the local host. I\'d like to add a timeout parameter to the method so that if the command being called doesn\'t finish in

17条回答
  •  时光取名叫无心
    2020-11-27 12:31

    There are various ways to do this, but I'd consider using an Executor-- it just helps you encapsulate passing the exit value or exception from the thread back to the original caller.

        final Process p = ...        
        Callable call = new Callable() {
        public Integer call() throws Exception {
            p.waitFor();
            return p.exitValue();
          }
        };
        Future ft = Executors.newSingleThreadExecutor().submit(call);
        try {
          int exitVal = ft.get(2000L, TimeUnit.MILLISECONDS);
          return exitVal;
        } catch (TimeoutException to) {
          p.destroy();
          throw to;
        }
    

    I think you can't get round the race condition whereby the wait times out, and then process terminates just before you call destroy().

提交回复
热议问题