javaredisquarkusfuturevert.x

how to avoid while loop while waiting for future complete?


I have a problem with a java future and an handler function. code example:

public HealthCheckResponse call() {

  String redisHost = this.configuration.getRedisHost();
  log.info("connect to redis host: {}", redisHost);
  
  Future<RedisConnection> redisConnectionFuture = Redis.createClient(Vertx.vertx(), redisHost).connect();
        while (!redisConnectionFuture.isComplete()) {
            log.debug("waiting for redis connection future complete: ({})", redisConnectionFuture.isComplete());
        }
        log.info("redis connection future completed, {} and succeded {}", redisConnectionFuture.isComplete(), redisConnectionFuture.succeeded());
        if (redisConnectionFuture.isComplete() && redisConnectionFuture.succeeded()) {
            return HealthCheckResponse.up("RedisCustomHealthCheck");
        }
        log.info("sending down RedisCustomHealthCheck");
        return HealthCheckResponse.down("RedisCustomHealthCheck");
    }

so my problem is that I have to check the redis connection. This is an async function so, I can set onSuccess and write my logic. there I can not return the HealtCheckResponse. Question, I don't want to wait with the while loop. What is a possible solution for this problem?


Solution

  • If you are not executing this on vertx event loop thread it is safe to use java.util.concurrent.CountDownLatch

    Here is an quick example for your use case:

    public HealthCheckResponse call() {
        Future<RedisConnection> redisConnectionFuture = Redis.createClient(Vertx.vertx(), redisHost).connect();
        CountDownLatch countDownLatch = new CountDownLatch(1);
    
        redisConnectionFuture.onComplete(x -> countDownLatch.countDown());
    
        try {
          countDownLatch.await();
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
    
        if (redisConnectionFuture.succeeded()) {
          return HealthCheckResponse.up("RedisCustomHealthCheck");
        } else {
          return HealthCheckResponse.down("RedisCustomHealthCheck");
        }
      }