Reputation: 1861
I am getting back into Java after a long long time so apologies if the question seems stupid. I am trying to use CompletableFuture to create a non-blocking call. I have a method that returns a boolean
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;
}
}
And i pass this function to completedFuture in this way:
CompletableFuture<Boolean> resultHandle =
CompletableFuture.supplyAsync(this.waitOnState("RUNNING", 100000));
resultHandle.thenAccept(result -> System.out.println(result));
But I get an error The method supplyAsync(Supplier<U>) in the type *CompletableFuture* is not applicable for the arguments (boolean)
The error persists even if I change the return type of my function to Boolean or Integer so I am sure I am invoking the CompletableFuture incorrectly
Upvotes: 2
Views: 4686
Reputation: 45319
You should rather give it a supplier, so don't invoke the method inline, rather make it a lambda expression:
CompletableFuture<Boolean> resultHandle =
CompletableFuture.supplyAsync(() ->
this.waitOnState("RUNNING", 100000));
() -> this.waitOnState("RUNNING", 100000)
is a lambda expression that the compiler can make a Supplier
from, but this.waitOnState("RUNNING", 100000)
is a boolean expression.
Upvotes: 2