java native Process timeout

前端 未结 6 1468
不思量自难忘°
不思量自难忘° 2020-11-27 14:31

At the moment I execute a native process using the following:

java.lang.Process process = Runtime.getRuntime().exec(command); 
int returnCode = process.waitF         


        
6条回答
  •  天命终不由人
    2020-11-27 15:08

    All other responses are correct but it can be made more robust and efficient using FutureTask.

    For example,

    private static final ExecutorService THREAD_POOL 
        = Executors.newCachedThreadPool();
    
    private static  T timedCall(Callable c, long timeout, TimeUnit timeUnit)
        throws InterruptedException, ExecutionException, TimeoutException
    {
        FutureTask task = new FutureTask(c);
        THREAD_POOL.execute(task);
        return task.get(timeout, timeUnit);
    }
    
    final java.lang.Process[] process = new Process[1];
    try {
        int returnCode = timedCall(new Callable() {
            public Integer call() throws Exception {
                process[0] = Runtime.getRuntime().exec(command); 
                return process[0].waitFor();
            }
        }, timeout, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        process[0].destroy();
        // Handle timeout here
    }
    

    If you do this repeatedly, the thread pool is more efficient because it caches the threads.

提交回复
热议问题