Note that there are some explanatory texts on larger screens.

plurals
  1. POFutures, TimeoutException, and Callables with finally blocks
    text
    copied!<p>Will a finally block withing a thread be called if the Callable is canceled via future.get(timeout, TimeUnit.SECONDS)?</p> <pre><code>class MyCallable implements Callable&lt;Future&lt;?&gt;&gt;{ public Future&lt;?&gt; call(){ Connection conn = pool.getConnection(); try { ... } catch(CatchExceptions ce){ } finally { conn.close(); } } } ... future.get(executionTimeoutSeconds, TimeUnit.SECONDS); </code></pre> <p>I am aware that finally will always be called, but i'm guessing i'm missing something regarding how threads are interrupted. Here is a test i ran that did not show my finally block being fired. </p> <pre><code>@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&lt;Void&gt; { @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!"); } } } </code></pre> <p>Looks like if i add awaitTermination it runs. This test passes...</p> <pre><code>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(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload