All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.clinia.utils.TaskUtils Maven / Gradle / Ivy

package com.clinia.utils;

import com.clinia.exceptions.*;
import java.util.function.IntUnaryOperator;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class TaskUtils {

  private TaskUtils() {
    // Empty.
  }

  public static final int DEFAULT_MAX_RETRIES = 50;
  public static final IntUnaryOperator DEFAULT_TIMEOUT = (int retries) -> Math.min(retries * 200, 5000);

  public static  T retryUntil(Supplier func, Predicate validate, int maxRetries, IntUnaryOperator timeout)
    throws CliniaRuntimeException {
    int retryCount = 0;
    while (retryCount < maxRetries) {
      T resp = func.get();
      if (validate.test(resp)) {
        return resp;
      }
      try {
        Thread.sleep(timeout.applyAsInt(retryCount));
      } catch (InterruptedException ignored) {
        // Restore interrupted state...
        Thread.currentThread().interrupt();
      }

      retryCount++;
    }
    throw new CliniaRetriesExceededException("The maximum number of retries exceeded. (" + (retryCount + 1) + "/" + maxRetries + ")");
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy