transform
is probably not going to do what you want. You mentioned that cancelling futureToListen
will cancel future
, and that's true. The problem is that the same is true of the reserve: When future
is cancelled, so too will futureToListen
be. That will mean that it never computes its result.
To solve this problem, you have a couple options:
- If you don't care about being able to cancel
future
, then changefutureToListen
to aSettableFuture
. Then have whoever cancelsfuture
also callfutureToListen.set(file)
. - If you do care about being able to cancel
future
, then changefutureToListen
to anAbstractFuture
that (a) exposesset()
(so that you can do what I recommend in (1)) and (b) implementsinterruptTask()
to callfuture.cancel()
.
There are other possible clever solutions that involve triggering the work whenever future
completes unsuccessfully, but I'm not sure I recommend then. I personally feel a little nervous about using "Future
was cancelled" as a signal for "work is successfully done." That's because the Future
could also be cancelled by an executor shutdown, for example. (Another reason: You'd need to be careful to distinguish between "threw an exception during execution" and "was cancelled.") For this reason, my suggested solutions are set up to call set()
directly rather than to trigger off any cancellation of the future.