質問

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?

役に立ちましたか?

解決

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.

他のヒント

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)

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top