【问题标题】:CompletableFuture - supply a method that returns bool value to supplyAsync callCompletableFuture - 提供一个将布尔值返回给 supplyAsync 调用的方法
【发布时间】: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&lt;U&gt;) in the type *CompletableFuture* is not applicable for the arguments (boolean)

即使我将函数的返回类型更改为 Boolean 或 Integer,错误仍然存​​在,因此我确定我错误地调用了 CompletableFuture

【问题讨论】:

    标签: java asynchronous concurrency nonblocking completable-future


    【解决方案1】:

    你应该给它一个供应商,所以不要内联调用方法,而是让它成为一个 lambda 表达式:

    CompletableFuture<Boolean> resultHandle = 
                CompletableFuture.supplyAsync(() -> 
                     this.waitOnState("RUNNING", 100000));
    

    () -&gt; this.waitOnState("RUNNING", 100000) 是一个 lambda 表达式,编译器可以从中生成 Supplier,但 this.waitOnState("RUNNING", 100000) 是一个布尔表达式。

    【讨论】:

    • 啊,这行得通!学习一门新语言就像再次成为一个孩子:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多