简体   繁体   中英

Concurrent read and write to BlockingQueue

I'm using a LinkedBlockingQueue in front of a database. One thread writes to the queue and another one reads from the queue.

Two concurrent writes should not be possible I think. But is it possible that one thread writes and the other thread reads at the same time from the queue? And if not, is there a queue providing this in Java?

Yes, it is possible that one thread is reading and one is writing at the same time.

LinkedBlockingQueue uses two locks for this purpose. One for taking items from queue and other for putting items.

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

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

The way of implementation on LinkedBlockingQueue is also discussed in its source file (line 77) .

/*
 * 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.
 */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM