Reputation: 626
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?
Upvotes: 1
Views: 82