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

标签 java lambda java-8 functional-programming generic-programming

我有一个函数可以给我一个服务状态:

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

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

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
}

类似的东西,但我需要它尽可能通用(调用的方法部分应该采用其他方法),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
}

然后您的供应商只需要返回truefalse。例如:

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

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

关于java - 如何使用 java 8 在超时的情况下调用另一个函数内的通用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55228398/

相关文章:

java - tomcat 启动时出现 OverlappingFileLockException

java - Alfresco 中的方面名称在 'Manage Aspect' 中显示为未定义

java - Primefaces 从 Backing 调用 ConfirmDialog

c# - 用 try catch 包装的动态 lambda

c# - 使用 lambda 函数获取列表中对象属性值的总和

lambda 的 C++ 模板类型推断

java - JLS语法如何匹配简单的字段访问(obj.f)?

java - 使用java流来代替复杂的代码

c# - Java中任务并行库的等价物

具有详细时区的 Java DateTimeFormatterBuilder