如果通过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();
}
}