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

前端 未结 17 1823
长发绾君心
长发绾君心 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:30

    For everybody using the executor framework: you are all forgetting to shutdown the executor. So change it to the following:

    ExecutorService service = Executors.newSingleThreadExecutor();
    try {
        Future ft = service.submit(call);
        try {
            int exitVal = ft.get(2000L, TimeUnit.MILLISECONDS);
            return exitVal;
        } catch (TimeoutException to) {
            p.destroy();
            throw to;
        }
    }
    finally {
        service.shutdown();
    }
    

    If you don't your program will keep an active non-daemon thread, ensuring your program will never exit until you call System.exit

提交回复
热议问题