【问题标题】:How to invoke a generic function inside another function with a timeout with java 8?java - 如何使用java 8在另一个函数中调用一个泛型函数超时?
【发布时间】:2019-08-09 05:40:38
【问题描述】:

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

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
}

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

【问题讨论】:

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


    【解决方案1】:

    具体使用您的示例:

    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() 或类似名称的调用之间暂停。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多