0

In a multithreaded environment, what is the policy regarding the take() method (removing an Object) for the various implementations of Java's BlockingQueue (for example LinkedBlockingQueue)?

Does the thread that calls take() first get the first available Object, e.g. is it a first come, first served, random, or is there some other policy describing how the queue is accessed by multiple threads? I cannot seem to find anything in the docs.

Gene
  • 46,253
  • 4
  • 58
  • 96
  • What "policy" are you looking for? Do you mean multiple threads blocked on a single `take()` method? – markspace Dec 06 '19 at 01:51
  • Yes. `BlockingQueue` follows `first-in-first-out` and is `thread-safe` Refer: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html#take() – Sunil Dabburi Dec 06 '19 at 02:41
  • Updated with a better explanation. – Spyridon Non Serviam Dec 06 '19 at 03:34
  • 1
    LinkedBlockingQueue is not fair. ArrayBlockingQueue has a constructor with a fairness parameter. I don't know about any other ones. It's a pretty rare requirement -- are you sure you need it? – Matt Timmermans Dec 06 '19 at 03:38
  • @MattTimmermans [`SynchronousQueue`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/SynchronousQueue.html) also supports optional fairness policy. – Andreas Dec 06 '19 at 03:51
  • When they mean thread safe, it means the thread that was able to access the queue is the one that gets the lock. So it’s a first come first serve basis – Sunil Dabburi Dec 06 '19 at 04:09
  • @MattTimmermans it would be helpful to know it, for statistic purposes. – Spyridon Non Serviam Dec 06 '19 at 08:48

0 Answers0