How to write 2 consequent recursions with Completable future?

76 views Asked by At

I have the following code which tries to get a /ready endpoint of a service until it returns OK and then makes a call to that service when it is available:

  @PostConstruct
  void registerMetadata() {
    CompletableFuture.runAsync(this::getServiceReady, executor)
        .thenRunAsync(() -> registerWithRetry(0), executor);
  }

  private void registerWithRetry(int retryAttempt) {
  serviceRegistrationOperations.registerService(serviceMetadataMedia)
        .thenAccept(data -> {
          this.isMetadataRegistered = true;
        }).whenComplete((data, ex) -> {
          if (ex != null) {
            Throwable cause = ExceptionUtils.cleanseTop(ex);
            String message = cause.getMessage();
            }
            int delayInSeconds = getDelaySecondsBeforeNextRetry(retryAttempt);
            log.error("Failed to register metadata: {}, will retry again in {} seconds", message, delayInSeconds, cause);
            CompletableFuture.runAsync(() -> registerWithRetry(retryAttempt + 1), new DelayedExecutor(delayInSeconds, TimeUnit.SECONDS, executor));
          }
        });
  }

  private CompletableFuture<Boolean> getServiceReady() {
    log.info("Getting the readiness of the service");
    if (this.exitFlag) {
      return CompletableFuture.completedFuture(null);
    }
    return healthOperations.getReadiness()
        .thenApply(isServiceReady -> {
         this.exitFlag = true;
          return true;
        }).whenComplete((result, ex) -> {
          if (ex != null) {
            log.error("service is not up");
            CompletableFuture.runAsync(() -> getServiceReady(), new DelayedExecutor(5, TimeUnit.SECONDS, executor));
          }
        });
  }

However, it seems that the code never waits for the first recursion to complete (meaning the healthOperations.getServiceReady() to return true). I want to make it so that it first waits for the first recursion to finish and then to go to the registerWithRetry method. Can you help me figure out how to write the first recursion so that the program waits for it and then moves on with the second one?

I tried different ways to achieve this. For my use case block(healthOperations.getServiceReady()) doesn't work, so my guess is that it has to be a chain of events.

0

There are 0 answers