我可以用CountDownLatch替换ReentrantLock和condition吗?

时间:2019-07-01 11:46:13

标签: java concurrency reentrantlock

我正在使用旧式图书馆,该图书馆提供以下示例作为示例。据我了解,您提供了一个回调对象,并且一旦库有答案,就会在其上调用方法。我必须等待答复,然后继续执行。在回调的一种方法中,我解析响应并将元素添加到集合中(我怀疑它必须是同步集合,作者只提到了这一点:“ onFailure可以由多个线程并发调用,因此请确保正确同步您的回调代码”)

private static List<MktDataPrice> requestMarket(XYZConnector xyzConnector, MktDataPerimeter perimeter) {

        final List<MktDataPrice> result = new Vector<MktDataPrice>();

        final ReentrantLock reentrantLock = new ReentrantLock();
        final Condition finishCondition = reentrantLock.newCondition();
        final AtomicBoolean finished = new AtomicBoolean(false);

        xyzConnector.request(new MktDataRequest(perimeter, today, yesterday), new MktDataCallback() {

            public void onFinish(String perimeterId) {
                LOGGER.info("On finish request ");
                try {
                    reentrantLock.lock();
                    finished.set(true);
                    finishCondition.signalAll();
                } finally {
                    reentrantLock.unlock();
                }
            }

            public void onFailure(String perimeterId, Throwable t) {
                LOGGER.error("On failure request market", t);
            }

            public void onBegin(String perimeterId) {
                LOGGER.info("On begin request market");
            }

            public void onData(String perimeterId, MktDataInfo data) {
               result.addAll(processData(data));  

            }
        });
        try {
            reentrantLock.lock();
            while (!finished.get()) {
                try {
                    finishCondition.await();
                } catch (InterruptedException e) {
                    LOGGER.error("Interrupted", e);
                }
            }
        } finally {
            reentrantLock.unlock();
        }

     return result;
    }

我正在尝试编写更简洁的内容,是否可以像下面的示例一样用CountDownLatch替换它,或者我丢失了某些内容?有没有更清洁的方法来实现这一点?

 public List<MktDataPrice> requestReply(MktDataRequest perimeter) {

        final CountDownLatch latch = new CountDownLatch(1);
        List<MarketDataPrice> results = new ArrayList<>();

        MktDataCallback callback = new MktDataCallback() {

        @Override
        public void onData(String perimeter, MktDataInfo sgibML_marketDataInfo) {
            results.addAll(getMktDataPriceFromSgibml(mktDataInfo));
        }

        @Override
        public void onBegin(String perimeter) {
        }

        @Override
        public void onFinish(String perimeter) {
            latch.countDown();
        }

        @Override
        public void onFailure(String perimeter, Throwable throwable) {
            latch.countDown();
        }
    };


    xyzConnector.request(perimeter, callback);

    try {
        latch.await();
    } catch (InterruptedException ex) {
        log.error("Could not wait to get response.." , ex);
    }

    return results;
}

0 个答案:

没有答案