【发布时间】: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