2

如果通过future.get(timeout,TimeUnit.SECONDS)取消Callable,是否会调用带有线程的finally块?

class MyCallable implements Callable<Future<?>>{
    public Future<?> call(){
        Connection conn = pool.getConnection();
        try {
            ... 
        } catch(CatchExceptions ce){
        } finally {
            conn.close();
        }
    } 
}

... 

future.get(executionTimeoutSeconds, TimeUnit.SECONDS);

我知道 finally 总是会被调用,但我猜我错过了一些关于线程如何被中断的东西。这是我运行的一个测试,它没有显示我的 finally 块被解雇了。

@Test
public void testFuture(){
    ExecutorService pool =  Executors.newFixedThreadPool(1);
    try {
        pool.submit(new TestCallable()).get(1, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (TimeoutException e) {
        e.printStackTrace();
    }
}

class TestCallable implements Callable<Void> {
    @Override
    public Void call() throws Exception {
        try{
        while(true){
            Thread.sleep(3000);
            break;
        }
        } catch (Exception e){
            System.out.println("EXCEPTION CAUGHT!");
            throw e;
        } finally {
            System.out.println("FINALLY BLOCK RAN!");
        }
    }

}

看起来如果我添加 awaitTermination 它会运行。这个测试通过...

public void testFuture(){
    ExecutorService pool =  Executors.newFixedThreadPool(1);
    try {
        pool.submit(new TestCallable()).get(1, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (TimeoutException e) {
        e.printStackTrace();
    }
    try {
        pool.awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
4

1 回答 1

2

future.get(...)不取消线程。它只等待线程完成,TimeoutException如果等待超时则抛出。

future.cancel(true) 导致线程被中断。这可能会也可能不会阻止您的线程处理。这取决于您所在try ...区域内发生的情况。例如,Thread.sleep(...),和其他方法在线程中断时Object.wait(...)抛出。InterruptedException否则,您需要检查线程中断标志

if (Thread.currentThread().isInterrupted()) {
    // maybe stop the thread or whatever you want
    return;
}

如果try进入该finally块,则始终调用该块(无论是否中断),除非存在某种 JVM 故障和崩溃。我怀疑你的线程根本没有被中断,所以继续运行。

于 2013-01-15T14:46:15.460 回答