java native进程超时

del*_*ber 44 java process

目前我使用以下方法执行本机进程:

java.lang.Process process = Runtime.getRuntime().exec(command); 
int returnCode = process.waitFor();
Run Code Online (Sandbox Code Playgroud)

假设代替等待程序返回,我希望在一定时间过去后终止.我该怎么做呢?

ZZ *_*der 52

所有其他响应都是正确的,但使用FutureTask可以使其更加健壮和高效.

例如,

private static final ExecutorService THREAD_POOL 
    = Executors.newCachedThreadPool();

private static <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit)
    throws InterruptedException, ExecutionException, TimeoutException
{
    FutureTask<T> task = new FutureTask<T>(c);
    THREAD_POOL.execute(task);
    return task.get(timeout, timeUnit);
}

try {
    int returnCode = timedCall(new Callable<Integer>() {
        public Integer call() throws Exception {
            java.lang.Process process = Runtime.getRuntime().exec(command); 
            return process.waitFor();
        }
    }, timeout, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    // Handle timeout here
}
Run Code Online (Sandbox Code Playgroud)

如果重复执行此操作,则线程池会更高效,因为它会缓存线程.


Ale*_*øld 21

如果您使用的是Java 8,则只需使用新的waitFor with timeout:

Process p = ...
if(!p.waitFor(1, TimeUnit.MINUTE)) {
    //timeout - kill the process. 
    p.destroy(); // consider using destroyForcibly instead
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*ler 19

这就是Plexus CommandlineUtils的用法:

Process p;

p = cl.execute();

...

if ( timeoutInSeconds <= 0 )
{
    returnValue = p.waitFor();
}
else
{
    long now = System.currentTimeMillis();
    long timeoutInMillis = 1000L * timeoutInSeconds;
    long finish = now + timeoutInMillis;
    while ( isAlive( p ) && ( System.currentTimeMillis() < finish ) )
    {
        Thread.sleep( 10 );
    }
    if ( isAlive( p ) )
    {
        throw new InterruptedException( "Process timeout out after " + timeoutInSeconds + " seconds" );
    }
    returnValue = p.exitValue();
}

public static boolean isAlive( Process p ) {
    try
    {
        p.exitValue();
        return false;
    } catch (IllegalThreadStateException e) {
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • Ewwww ...所以每10毫秒依赖p.exitValue()抛出IllegalThreadStateException来表示"仍在运行"? (8认同)
  • 为什么是循环?为什么不运行一个 TimerTask ,它只会在超时到期时检查“活跃度”一次? (2认同)

mic*_*son 6

那么Groovy的方式呢

public void yourMethod() {
    ...
    Process process = new ProcessBuilder(...).start(); 
    //wait 5 secs or kill the process
    waitForOrKill(process, TimeUnit.SECONDS.toMillis(5));
    ...
}

public static void waitForOrKill(Process self, long numberOfMillis) {
    ProcessRunner runnable = new ProcessRunner(self);
    Thread thread = new Thread(runnable);
    thread.start();
    runnable.waitForOrKill(numberOfMillis);
}

protected static class ProcessRunner implements Runnable {
    Process process;
    private boolean finished;

    public ProcessRunner(Process process) {
        this.process = process;
    }

    public void run() {
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            // Ignore
        }
        synchronized (this) {
            notifyAll();
            finished = true;
        }
    }

    public synchronized void waitForOrKill(long millis) {
        if (!finished) {
            try {
                wait(millis);
            } catch (InterruptedException e) {
                // Ignore
            }
            if (!finished) {
                process.destroy();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)