A BlockingQueue is an interface, which is a queue that blocks when you try to dequeue from it and the queue is empty, or if you try to enqueue items to it and the queue is already full. A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue. A thread trying to enqueue an item in a full queue is blocked until some other thread makes space in the queue, either by dequeuing one or more items or clearing the queue completely.
BlockingQueue methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future: one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up.
|Operation||Throws Exception||Special Value||Blocks||Times out|
|Insert||add()||offer(e)||put(e)||offer(e, time, unit)|
BlockingQueue can be bounded or unbounded. A bounded BlockingQueue is one which is initialized with initial capacity.
BlockingQueue<String> bQueue = new ArrayBlockingQueue<String>(2);
Any calls to a put() method will be blocked if the size of the queue is equal to the initial capacity defined.
An unbounded Queue is one which is initialized without capacity, actually by default it initialized with Integer.MAX_VALUE.
Some common implementations of
Now let's look at an example of
BlockingQueue<String> bQueue = new ArrayBlockingQueue<>(2); bQueue.put("This is entry 1"); System.out.println("Entry one done"); bQueue.put("This is entry 2"); System.out.println("Entry two done"); bQueue.put("This is entry 3"); System.out.println("Entry three done");
This will print:
Entry one done Entry two done
And the thread will be blocked after the second output.