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

一个人想着一个人 提交于 2019-12-21 07:09:05

问题


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?


回答1:


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.




回答2:


You can use ArrayBlockingQueue. This is a bounded blocking queue backed by an array. This queue orders elements FIFO (first-in-first-out). ArrayBlockingQueue is a classic "bounded buffer", in which a fixed-sized array holds elements inserted by producers and extracted by consumers. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ArrayBlockingQueue.html (for those who also stepped on a rake)




回答3:


From the Javadoc:

.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



来源:https://stackoverflow.com/questions/9151871/queue-full-on-depth-of-the-blocking-queue-clarification-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!