在BlockingQueue中阻塞的线程

时间:2014-01-19 00:50:18

标签: java multithreading blockingqueue

我有一个容量为1的BlockingQueue。它存储收到的股票的最后价格。价格保留在队列中,直到客户端轮询队列。然后,我有一个名为getLatestPrice()的方法,它应该返回该股票的最新价格。我的问题是,如果客户端尚未对其进行轮询,则最新价格可能不在队列中。它可能在一个被阻塞的线程中。如果它被阻止,那么返回最新价格的最佳解决方案是什么?谢谢。

private final BlockingQueue<PriceUpdate> latest;
private final long pollTimeout = 2;
private TimeUnit pollTimeUnit = TimeUnit.SECONDS;

public SaveListener(int capacity) {
     latest = new ArrayBlockingQueue<PriceUpdate>(capacity, true);
}

public void newPrice(PriceUpdate priceUpdate) {
    try {
        latest.put(priceUpdate);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public PriceUpdate getNewPrice() {
    try {
        return latest.poll(pollTimeout, pollTimeUnit);                  } 
catch (InterruptedException e) {
        return null;
    }
} 

getLatestPrice()调用getNewPrice但是它没有返回任何值,但我知道队列中存储了一个值。

2 个答案:

答案 0 :(得分:1)

使AtomicReference保持最新值,它不会阻止更新。

答案 1 :(得分:0)

添加另一个BlockingQueue,使newPrice()在put()之前替换(清除/添加)此队列中的值。使getNewPrice()轮询此队列。

相关问题