CompletableFuture和订单发生

时间:2018-12-28 23:43:37

标签: java jls happens-before

我打算创建2个线程来进行一些计算,然后检查(每个线程) other 是否也完成了其计算,否则直接退出。当线程1发现 other (线程2)也已完成其计算时,线程1应基于线程2的结果继续进行其他计算(否则将退出)。

所以我打算将下面的Runnable和2个线程一起使用:

me = new CompletableFuture<>();
theOther = new CompletableFuture<>();
executorService.submit(createWorker(data, true, me, theOther));
executorService.submit(createWorker(data++, false, theOther, me));

Runnable的创建方式如下:

private Runnable createWorker(int data, boolean callRegion1,
                    CompletableFuture<Payment> me,
                    CompletableFuture<Payment> theOther) {
    return () -> {
        Payment myPayment;
        try {
            myPayment = postData(data, callRegion1);
            me.complete(myPayment);
        } catch (Throwable ex) {
            me.completeExceptionally(ex);
            // comparison with theOther no longer make sense
            return;
        }
        // skip comparison when myPayment is null
        if (myPayment == null) {
            log.error("myPayment == null for data = {}", data);
            return;
        }
        // get otherPayment and ignore exceptions
        Payment otherPayment = theOther.getNow(absentPayment);
        // skip comparison when otherPayment is null or not yet available
        if (otherPayment == null || otherPayment == absentPayment) {
            return;
        }
        // doing the comparison here
        if (otherPayment.getData() + myPayment.getData() != 0) {
            log.error("M/M or M/SM for data = {}", data);
            System.exit(-1);
        }
    };
}

创建的Runnable未显式同步,因此我担心下面的代码:

theOther.getNow(absentPayment);
两个线程可能同时将

评估为absentPayment,这对我不利(我们将其命名为糟糕的情况)。

问:糟糕的情况是否可能?为什么?如果不可能,又为什么不呢?

0 个答案:

没有答案