Java ArrayBlockingQueue put() Method

The put() method of ArrayBlockingQueue adds the defined element at the tail of this queue. It waits till the space becomes available if queue is full.

Syntax:

Parameters:

e - This is the element to be added.

Specified By:

The put() method of ArrayBlockingQueue class is specified by put() method in interface BlockingQueue.

Throws:

The put() method throws:

  1. NullPointerException - If the element defined holds null value.
  2. InterruptedException - If method is disrupted while waiting.

Example 1

Output:

Elements in queue : [67, 109, 76, 876, 2]

Example 2

Output:

Error:(9, 18) java: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
Error:(10, 18) java: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
Error:(11, 18) java: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
Error:(12, 18) java: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown

Either we should add exception to method signature or we should surround the put() method with try catch, else it will give above described error.

Example 3

Output:

Exception in thread "main" java.lang.NullPointerException
	at java.util.concurrent.ArrayBlockingQueue.checkNotNull(ArrayBlockingQueue.java:150)
	at java.util.concurrent.ArrayBlockingQueue.put(ArrayBlockingQueue.java:348)
	at com.javaTpoint.ArrayBlockingQueuePutExample2.main(ArrayBlockingQueuePutExample2.java:13)

If the specified element is null, it will give null pointer exception as shown above.