guava icon indicating copy to clipboard operation
guava copied to clipboard

"finally" for futures

Open benjaminp opened this issue 3 years ago • 2 comments

Consider the following simple snippet that does some work with a closeable resource:

Closeable c = allocateResource();
try {
  doWork(c);
} finally {
  c.close();
}

If we want to make doWork asynchronous, this code can be seemingly straightforwardly futurized with the help of addListener:

Closeable c = allocateResource();
ListenableFuture<Void> f = executor.submit(() -> doWork(c));
f.addListener(c::close, executor);

My concern with this translation is that if f is canceled, c.close may execute concurrently with doWork. That's a problem if c is not thread-safe. Ideally, c.close would be called when the task associated to f is not running, either because it finished or was preventing from even starting by cancellation.

I apologize if I've missed an existing pattern to deal with this situation. I looked at ClosingFuture—this issue is a sister of the one that prompted #3975—, but it seems that ClosingFuture is mostly sugar over the above addListener snippet and wouldn't prevent simultaneous execution of future tasks and closers during cancellation.

benjaminp avatar May 12 '22 05:05 benjaminp

This makes me think that we should change ClosingFuture to guarantee that closing doesn't start until the future is really done, meaning on cancelation it would wait for any running task to complete. I don't know how feasible that is, though.

netdpb avatar May 17 '22 15:05 netdpb