This question is related with one of my earlier questions..
In there the blocking nature is mentioned as an advantage.
I tried to develop some simple code to demonstrate the blocking nature but I got stuck. I just tried to make a BlockingQueue
of size 4 and tried to add 5 elements and ended up with a java.lang.IllegalStateException
. Can someone show me a code example for blocking nature of BlockingQueue
?
public static void main(String[] args) {
BlockingQueue<String> bq = new LinkedBlockingQueue<String>(4);
try {
bq.offer("A");
bq.offer("B");
bq.offer("C");
bq.offer("D");
bq.offer("E");
System.out.println("1 = " + bq.take());
System.out.println("2 = " + bq.take());
System.out.println("3 = " + bq.take());
System.out.println("4 = " + bq.take());
System.out.println("5 = " + bq.take());
System.out.println("6 = " + bq.take());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
I used this code segment. In this case I am trying to put 5 elements to a queue with size 4. In this case 4 elements (A,B,C,D) should be added to queue. Then I am calling take()
method while printing. Shouldn't "E" be inserted automatically to the queue when I call System.out.println("1 = " + bq.take());
? Because it gets one free slot?