如何在 java 8 超时的情况下调用另一个函数内的通用函数?

How to invoke a generic function inside another function with a timeout with java 8?

我有一个功能可以提供服务状态:

public ServiceState getServiceState(){
      return someService().getState(); //currently state return "NOTACTIVE"
} 

并且当我在系统上调用某个方法时,服务应该在 x 时间后(未知时间)处于活动状态:

someService().startService(); //after a while, the state of the service should be active

如果我只想检查一次服务状态,我会这样做:

public boolean checkCurrentState(String modeToCheck){
      return getServiceState() == modeToCheck; 
}

checkCurrentState("ACTIVE"); //return true or false depends on the state

问题是,状态需要一些时间来改变,所以我需要以下内容:

我需要检查当前状态(在我定义的 x 秒的 while 循环中),如果 x 秒后服务仍处于 "NOTACTIVE" 模式,我将抛出某种异常终止我的程序。

于是我想到了以下解决方案: 一个有 2 个变量的方法:一个变量表示可以在方法内部调用的通用函数,一个变量是我允许它继续检查的时间:(伪代码)

public void runGenericForXSeconds(Func function,int seconds) throws SOMEEXCEPTION{
      int timeout = currentTime + seconds; //milliseconds
      while (currentTime < timeout){
           if (function.invoke()) return; //if true exits the method, for the rest of the program, we are all good
      }
      throw new SOMEEXCEPTION("something failed"); //the function failed
}

类似的东西,但我需要它尽可能通用(调用的方法部分应该采用其他方法),Java8 个 lambda 是解决方案的一部分?

具体使用您的示例:

public void runGenericForXSeconds(BooleanSupplier supplier, int seconds) throws SOMEEXCEPTION {
    int timeout = currentTime + seconds; // milliseconds
    while (currentTime < timeout) {
        if (supplier.getAsBoolean())
            return; // if true exits the method, for the rest of the program, we are all good
    }
    throw new SOMEEXCEPTION("something failed"); // the function failed
}

那么您的供应商只需要 return truefalse。例如:

runGenericForXSeconds(() -> !checkCurrentState("ACTIVE"), 100);

请注意,您有一个繁忙的循环。除非您明确想要这样做,否则您可能希望在使用 Thread.sleep() 或类似方法的调用之间暂停。