lets say we have two threads with are connected by a ConcurrentLinkedQueue. What I want is something like a handler on the queue so that one thread knows when the other queue has added soemthing to the queue and to poll it. Is that possible?
-
Yes it is possible. Look at http://stackoverflow.com/questions/435069/java-util-concurrentlinkedqueue/435941#435941 – Natalia Apr 04 '17 at 12:36
-
If you use a Blocking queue, you can just call `take` on it. It will return when an element is available. – john16384 Apr 04 '17 at 12:36
-
but I want it to be async – user3133542 Apr 04 '17 at 12:40
-
1Then you need a spin, you cannot get both blocking and async features. – John Vint Apr 04 '17 at 15:01
1 Answers
Normally a ConcurrentLinkedQueue
is used when there is at least one producer on a thread, and at least one consumer on a different thread.
The consumer will process the element as soon as they are available, to do so the read operation on the queue blocks, sometimes for a limited amount of time.
Depending on the application you can have a single producer and many consumer, or viceversa.
Blocking achieves exactly your requirement (the consumer thread knows when an element is inserted).
The fact that the consumer thread blocks is not a problem unless is your main process thread or unless you are planning to build several hundred concurrent consumers.
So, Queue#take() or Queue#poll(long timeout,TimeUnit unit) is your friend here, if you just run it on dedicated Thread.

- 2,646
- 15
- 18