Say I have a method getCloseableResource()
which might take an unbounded amount of time to complete and returns something that needs to be closed or cleaned up.
I want to submit a task to an executorService to get the closeable resource but only wait a limited amount of time.
Future<CloseableResource> crFuture = executorService.submit(() -> getCloseableResource());
CloseableResource cr = crFuture.get(TIMEOUT, TimeUnit.MILLISECONDS);
catch (TimeoutException e) {
// abandon the attempt
}
The problem is that if I abandon waiting, I'll never be able to close the resource since I won't have a handle to it and the resource will never get cleaned up properly.
Is there some mechanism to specify cleanup code to execute when getCloseableResource returns so that I can abandon waiting for it AND make sure it is disposed of cleanly? Or maybe there is a more advance construct rather than an executor service.