0

How can I in the method stopTask() set CompletableFuture complete or failure operation if I had an exception in that method? I have some code:

private static class SenderTask implements Runnable {
    private final Sender sender;

    private ScheduledFuture<?> task;

    @Override
    public void run() {
        try {
            LOGGER.debug("SenderTask {} calling.", sender.getName());
            sender.process();
        } catch (Exception e) {
            LOGGER.error(e);
        }
    }

    public CompletableFuture<SenderTask> stopTask() {
        return CompletableFuture.supplyAsync(() -> {
            task.cancel(false);
            LOGGER.info("Sender {} try stopping.", sender.getName());
            try {
                    task.get(sender.getSenderConfig().getTimeoutConfig().getSendFileTimeout(),` TimeUnit.MILLISECONDS);
                } catch (InterruptedException | ExecutionException | TimeoutException e) {
                    LOGGER.error(e);
                }
                return this;
        });
    }
}

I need to know when my task was stopped.

Rakesh
  • 4,004
  • 2
  • 19
  • 31
John
  • 1,375
  • 4
  • 17
  • 40

1 Answers1

0

Could use handle like this:

public CompletableFuture<SenderTask> stopTask() {
   return CompletableFuture.supplyAsync(() -> {
      task.cancel(false);
      LOGGER.info("Sender {} try stopping.", sender.getName()); task.get(sender.getSenderConfig().getTimeoutConfig().getSendFileTimeout(),TimeUnit.MILLISECONDS);
      return this;
  }).handle((res, ex) -> {
      if(ex != null) {
          LOGGER.error(ex);
          ...
      }
      return res;
    });
}
Alon
  • 51
  • 1
  • 9