Are LinkedBlockingQueue's insert and remove methods thread safe?

后端 未结 3 490
悲&欢浪女
悲&欢浪女 2020-12-03 00:34

I\'m using LinkedBlockingQueue between two different threads. One thread adds data via add, while the other thread receives data via take

相关标签:
3条回答
  • 2020-12-03 00:50

    Simply Yes, its definitely thread safe otherwise it wouldn't have qualified as a candidate for storing element for ThreadPoolExecutor.

    Simply add and retrieve element without worrying about concurrency for BlockingQueue.

    0 讨论(0)
  • 2020-12-03 01:06

    Yes. From the docs:

    "BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c."

    0 讨论(0)
  • 2020-12-03 01:10

    Yes, BlockingQueue methods add() and take() are thread safe but with a difference.

    add () and take() method uses 2 different ReentrantLock objects.

    add() method uses

    private final ReentrantLock putLock = new ReentrantLock();
    

    take() method uses

    private final ReentrantLock takeLock = new ReentrantLock();
    

    Hence, simultaneous access to add() method is synchronized. Similarly, simultaneous access to take() method is synchronized.

    But, simultaneous access to add() and take() method is not synchronized since they are using 2 different lock objects (except during edge condition of queue full / empty).

    0 讨论(0)
提交回复
热议问题