【问题标题】:Concurrent read and write to BlockingQueue并发读写 BlockingQueue
【发布时间】:2017-06-22 10:30:45
【问题描述】:

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

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

【问题讨论】:

  • 是的。 LinkedBlockingQueue 不仅仅是一个同步的LinkedList
  • 你可以读一下javadoc,里面都有讨论。

标签: java queue blockingqueue


【解决方案1】:

是的,有可能一个线程在阅读而一个线程同时在写作

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 上的实现方式也在其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.
 */

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多