public CompletableFuture withLock()

in src/main/java/com/ericsson/gerrit/plugins/highavailability/index/IndexEventLocks.java [41:79]


  public CompletableFuture<?> withLock(
      IndexTask id, IndexCallFunction function, VoidFunction lockAcquireTimeoutCallback) {
    String indexId = id.indexId();
    Semaphore idSemaphore = getSemaphore(indexId);
    try {
      log.atFine().log("Trying to acquire %s", id);
      if (idSemaphore.tryAcquire(WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
        log.atFine().log("Acquired %s", id);
        return function
            .invoke()
            .whenComplete(
                (result, error) -> {
                  try {
                    log.atFine().log("Trying to release %s", id);
                    idSemaphore.release();
                    log.atFine().log("Released %s", id);
                  } catch (Throwable t) {
                    log.atSevere().withCause(t).log("Unable to release %s", id);
                    throw t;
                  }
                });
      }

      String timeoutMessage =
          String.format(
              "Acquisition of the locking of %s timed out after %d msec: consider increasing the number of shards",
              indexId, WAIT_TIMEOUT_MS);
      log.atWarning().log(timeoutMessage);
      lockAcquireTimeoutCallback.invoke();
      CompletableFuture<?> failureFuture = new CompletableFuture<>();
      failureFuture.completeExceptionally(new InterruptedException(timeoutMessage));
      return failureFuture;
    } catch (InterruptedException e) {
      CompletableFuture<?> failureFuture = new CompletableFuture<>();
      failureFuture.completeExceptionally(e);
      log.atSevere().withCause(e).log("Locking of %s was interrupted; giving up", indexId);
      return failureFuture;
    }
  }