【发布时间】:2018-06-14 23:09:58
【问题描述】:
在很长一段时间后我又回到了 Java,如果这个问题看起来很愚蠢,我深表歉意。我正在尝试使用 CompletableFuture 创建一个非阻塞调用。我有一个返回布尔值的方法
public boolean waitOnState(final String targetState, final long waitMs) {
long begin = System.nanoTime()/1000000;
synchronized (stateLock) {
long elapsedMs = 0L;
logger.debug(this.storeName + "-" + this.getStreamState().toString());
while (!this.getStreamState().toString().equals(targetState)) {
if (waitMs > elapsedMs) {
long remainingMs = waitMs - elapsedMs;
try {
logger.debug("Waiting on stream to be in run state in "+remainingMs);
stateLock.wait(remainingMs);
} catch (final InterruptedException e) {
// it is ok: just move on to the next iteration
}
} else {
logger.debug("Cannot transit to target state");
return false;
}
elapsedMs = System.nanoTime()/1000000 - begin;
}
logger.debug("State is running - "+this.storeName);
return true;
}
}
我以这种方式将此函数传递给 completedFuture:
CompletableFuture<Boolean> resultHandle =
CompletableFuture.supplyAsync(this.waitOnState("RUNNING", 100000));
resultHandle.thenAccept(result -> System.out.println(result));
但我收到一个错误The method supplyAsync(Supplier<U>) in the type *CompletableFuture* is not applicable for the arguments (boolean)
即使我将函数的返回类型更改为 Boolean 或 Integer,错误仍然存在,因此我确定我错误地调用了 CompletableFuture
【问题讨论】:
标签: java asynchronous concurrency nonblocking completable-future