java - Cancellation of CompletableFuture controlled by ExecutorService -
i have executorservice
forwards computed data completablefuture
:
class dataretriever { private final executorservice service = ...; public completablefuture<data> retrieve() { final completablefuture<data> future = new completablefuture<>(); service.execute(() -> { final data data = ... fetch data ... future.complete(data); }); return future; } }
i want client/user able cancel task:
final dataretriever retriever = new dataretriever(); final completablefuture<data> future = retriever().retrieve(); future.cancel(true);
this not work, cancels outer completablefuture
, not inner future scheduled in executor service.
is somehow possible propagate cancel()
on outer future inner future?
completablefuture#cancel
serves purpose of marking completablefuture
cancelled. nothing notify executing task stop, because has no relationship such task.
the javadoc hints @ this
mayinterruptifrunning
- value has no effect in implementation because interrupts not used control processing.
the inner future in example future
, not completablefuture
, , have relation executing runnable
(or callable
). internally, since know thread
task executing on, can send interrupt
attempt stop it.
one option return tuple of sorts (eg. pojo) provides reference both completablefuture
, future
returned executorservice#submit
. can use future
cancel
if need to. you'd have remember cancel
or complete
completablefuture
other parts of code don't remain blocked/starved forever.
Comments
Post a Comment