如何将完成或失败设置为可压缩未来



如果我在该方法中有异常,如何在方法stopTask((中设置CompletableFuture完成或失败操作?我有一些代码:

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;
        });
    }
}

我需要知道我的任务何时停止。

可以使用这样的句柄:

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;
    });
}

最新更新