1
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Connection> task = () -> getConnection(); // a complicated method but safe from resource leaks
try (Connection connection = timeOut == null
        ? executor.submit(task).get()
        : executor.submit(task).get(timeOut.toMillis(), TimeUnit.MILLISECONDS)) {
    // business logic
} catch (SQLException e) {
    // log
} catch (InterruptedException e) {
    // log
    Thread.currentThread().interrupt();
} catch (ExecutionException e) {
    // log
} catch (Exception e) {
    // log
} finally {
    executor.shutdownNow();
}

I have a piece of code which is supposed to fail if getConnection() takes too long, I am new to combining resource management with concurrency, is there any risk of resource leak if I implement it like this? Is there a better way to do it?

Teddy Tsai
  • 414
  • 1
  • 13
  • Possibly. If the `Future#get(long,TimeUnit)` call throws a `TimeoutException`, that doesn't stop the background task from continuing. Which means probably it will return a `Connection` eventually. But it won't be managed by the _try-with-resources_ statement. This means it will remain open until it is GC'd, assuming it is eligible to be GC'd (and the `Connection` implementation releases any allocated resources upon being GC'd). – Slaw Dec 30 '22 at 08:27
  • 1
    Likely you should catch the `TimeoutException` and then call `theFuture.cancel(true)`. Make sure to check the result of calling the cancel method, as between the exception being thrown and you calling cancel, the task may have completed (normally or exceptionally). Though whether or not calling `cancel(true)` has the desired effect depends on if your code reacts to cancellation (note the `true` argument means the thread running the task is interrupted, assuming the task could be cancelled). – Slaw Dec 30 '22 at 08:29
  • 1
    I would recommend using a connection pool that can handle the timeout for you, such as [HikariCP](https://github.com/brettwooldridge/HikariCP). – Tim Moore Dec 30 '22 at 09:36

0 Answers0