12

Is there a synchronized Queue class in Java? I'm looking for something like Vector (which is synchronized) vs ArrayList (which is not), but instead of implementing the List interface, I'm looking for it to implement Queue.

Note that there is no Collections.synchronizedQueue method to wrap an unsynchronized queue and make it synchronized.

rghome
  • 8,529
  • 8
  • 43
  • 62
Shelef
  • 3,707
  • 6
  • 23
  • 28
  • ConcurrentLinkedDeque – CodeClown42 Mar 17 '13 at 12:44
  • If you look through the docs of the classes that extend https://docs.oracle.com/javase/7/docs/api/java/util/AbstractQueue.html you'll probably find what you're looking for. And https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html http://stackoverflow.com/questions/2695426/are-linkedblockingqueues-insert-and-remove-methods-thread-safe – rogerdpack Apr 08 '15 at 19:37
  • This seems like a very valid question, since Queue seems to be different from other Java collections in this respect. I am going to request that it is re-opened, having edited to clarify the question a little. – rghome Dec 04 '17 at 13:54

3 Answers3

6

Look at ArrayBlockingQueue and another BlockingQueue implementations.

From documentation:

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

bsiamionau
  • 8,099
  • 4
  • 46
  • 73
  • 4
    This is a blocking queue, which is not what was requested. – rghome Dec 04 '17 at 13:55
  • 1
    @rghome I believe OP wanted to find thread-safe implementation, in this case my answer is correct – bsiamionau Dec 05 '17 at 05:15
  • 3
    I was concerned about the blocking behaviour. If the reader/writer blocks, then this is very different behaviour than in a standard non-blocking queue. But reading the API, I think this is optional and you can read/write non-blocking as well. So you are correct. – rghome Dec 05 '17 at 08:15
  • It is possible to avoid blocking, but ArrayBlockingQueue has a fixed capacity. – NateS Jun 15 '18 at 20:27
  • This answer is missing the point: `BlockingQueue implementations are thread-safe.` [source](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html) – cdalxndr Apr 30 '21 at 23:26
1

You can use 'BlockingQueue', below link may help you to get better idea about it

BlockingQueue, Queue Implementations

DwB
  • 37,124
  • 11
  • 56
  • 82
Vikas Singh
  • 2,838
  • 5
  • 17
  • 32
-2

How about SynchronousQueue? Refer: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/SynchronousQueue.html

Ezhil V
  • 894
  • 5
  • 11