Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedBlockingQueue and addAll()

Tags:

java

If an attempt to add a collection to a blocking queue that exceeds the blocking queue's remaining size, what is supposed to happen? This isn't clear from the documentation I've read so far.

     LinkedBlockingQueue<Integer> foo = new LinkedBlockingQueue<Integer>(3);
        foo.add(1);
        foo.add(2);
        LinkedBlockingQueue<Integer> tenElements = new LinkedBlockingQueue<Integer(10); 
        for(int i = 0; i < 10; i++)
            tenElements.add(i);   

        foo.addAll(collectionWith10elements);
like image 677
paiego Avatar asked Jan 26 '23 11:01

paiego


1 Answers

The documentation of add() state that an IllegalStateException is thrown if the queue is full:

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

When you try the following code:

public static void main(String[] args) throws Exception {
    ArrayList<Integer> l = new ArrayList<Integer>();
    l.add(10);
    l.add(20);
    l.add(30);
    l.add(40);
    l.add(50);
    LinkedBlockingQueue<Integer> foo = new LinkedBlockingQueue<Integer>(3);
    foo.add(1);
    foo.add(2);
    foo.addAll(l);
}

You will get the following exception:

Exception in thread "main" java.lang.IllegalStateException: Queue full
    at java.util.AbstractQueue.add(AbstractQueue.java:98)
    at java.util.AbstractQueue.addAll(AbstractQueue.java:187)
    at Test.main(Test.java:16)
like image 166
Progman Avatar answered Jan 30 '23 03:01

Progman