Queue Full, On depth of the Blocking Queue, clarification needed

James Raitsev picture James Raitsev · Feb 5, 2012 · Viewed 19.9k times · Source

When populating the queue from the contents of the file, depth does not seem to ever increase, as elements are not added in this implementation.

    BlockingQueue<String> q = new SynchronousQueue<String>();
            ...
        fstream = new FileInputStream("/path/to/file.txt");
            ...
        while ((line = br.readLine()) != null) {
            if (q.offer(line))
                System.out.println("Depth: " + q.size()); //0
        }

When replacing offer with add, exception if thrown

Exception in thread "main" java.lang.IllegalStateException: Queue full
  ...

What am i doing wrong please? Why is the queue full immediately, upon insertion of the first element?

Answer

Mat picture Mat · Feb 5, 2012

Check the documentation for SynchronousQueue:

A blocking queue in which each put must wait for a take, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one. You cannot peek at a synchronous queue because an element is only present when you try to take it; you cannot add an element (using any method) unless another thread is trying to remove it; you cannot iterate as there is nothing to iterate. The head of the queue is the element that the first queued thread is trying to add to the queue; if there are no queued threads then no element is being added and the head is null. For purposes of other Collection methods (for example contains), a SynchronousQueue acts as an empty collection. This queue does not permit null elements.

You need to have consumers set up and waiting before you can try to add to the queue.

The offer method doesn't do anything if there are no consumers:

Inserts the specified element into this queue, if another thread is waiting to receive it.