如何使用java 8在另一个函数中调用超时的通用函数?

如何使用java 8在另一个函数中调用超时的通用函数?,java,lambda,java-8,functional-programming,generic-programming,Java,Lambda,Java 8,Functional Programming,Generic Programming,我有一个功能,可以让我处于服务状态: public ServiceState getServiceState(){ return someService().getState(); //currently state return "NOTACTIVE" } 当我在系统上调用某个方法时,服务应在x个时间量(未知时间)后处于活动状态: 如果我只想检查一次服务状态,我会这样做: public boolean checkCurrentState(String modeToCheck){

我有一个功能,可以让我处于服务状态:

public ServiceState getServiceState(){
      return someService().getState(); //currently state return "NOTACTIVE"
} 
当我在系统上调用某个方法时,服务应在x个时间量(未知时间)后处于活动状态:

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

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

checkCurrentState("ACTIVE"); //return true or false depends on the state
问题是,状态需要一些时间才能改变,所以我需要以下几点:

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

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

public void runGenericForXSeconds(Func函数,int-seconds)引发一些异常{
int timeout=currentTime+seconds;//毫秒
while(当前时间<超时){
if(function.invoke())return;//如果true退出该方法,对于程序的其余部分,我们都很好
}
抛出新的SOMEEXCEPTION(“something failed”);//函数失败
}

诸如此类,但我需要尽可能通用(调用的方法部分应采用其他方法),Java 8 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
}
请注意,您有一个繁忙的循环。除非您明确希望这样做,否则您可能希望使用
Thread.sleep()
或类似工具在调用之间暂停

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
}
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
}
runGenericForXSeconds(() -> !checkCurrentState("ACTIVE"), 100);