并发读写BlockingQueue

时间:2017-06-22 10:30:45

标签: java queue blockingqueue

我在数据库前使用LinkedBlockingQueue。一个线程写入队列,另一个线程从队列中读取。

我认为不应该有两个并发写入。但是有可能一个线程写入而另一个线程同时从队列中读取吗?如果没有,是否有一个队列在Java中提供这个?

1 个答案:

答案 0 :(得分:2)

是的,一个帖子可能,一个同时写

LinkedBlockingQueue为此目的使用了两个锁。一个用于从队列中取出物品,另一个用于放置物品。

/** Lock held by put, offer, etc */
private final ReentrantLock putLock = new ReentrantLock();

/** Lock held by take, poll, etc */
private final ReentrantLock takeLock = new ReentrantLock();

LinkedBlockingQueue上也讨论了/* * A variant of the "two lock queue" algorithm. The putLock gates * entry to put (and offer), and has an associated condition for * waiting puts. Similarly for the takeLock. The "count" field * that they both rely on is maintained as an atomic to avoid * needing to get both locks in most cases. Also, to minimize need * for puts to get takeLock and vice-versa, cascading notifies are * used. When a put notices that it has enabled at least one take, * it signals taker. That taker in turn signals others if more * items have been entered since the signal. And symmetrically for * takes signalling puts. Operations such as remove(Object) and * iterators acquire both locks. */ 的实施方式。

/map/color;lat=50;long=20;scale=32000