Java ArrayBlockingQueue
ArrayBlockingQueue is an implementation of the BlockingQueue, Which is backed by the Array Data Structure. ArrayBlockingQueue can be initialized by the specified limit.
Specified limit should be with in the limit of primitive data type int , the following are constructors of the ArrayBlockingQueue.
- ArrayBlockingQueue(int capacity)
- ArrayBlockingQueue(int capacity, boolean fair)
- ArrayBlockingQueue(int capacity, boolean fair,Collection<? extends E> c)
capacity is the limit in terms of how many elements can be inserted in ArrayBlockingQueue at max, fair is true means queue accessed will be done in the FIFO otherwise order policy will be unspecified and Collection is the list of elements which needs to be inserted into the queue at the time of initialization.
This Collection size should be less than the capacity of the ArrayBlockingQueue otherwise this will lead to an IllegalArgumentException.
The following are the most commonly used methods in the ArrayBlockingQueue.
Insert Operation
- add(e) If this operation is not possible immediately then an exception will be thrown.
- offer(e) If this operation is not possible immediately then it will return false otherwise true.
- put(e) This operation will wait until it gets success in other words it will block the current thread until operation gets success.
- offer(e, time, unit) This operation is not possible immediately then it will until the specified time limit for success otherwise it will returns false
Remove Operation
- remove(Object e) If the queue contains the element e then it will remove that element and return true otherwise return false. If the Object e is not compatible with Queue will lead to an exception
- poll() It will retrieve and removes the head of the queue, in case Queue is empty return null.
- take() It will retrieve and removes the head of the queue, in case Queue is empty thread will wait until the element becomes available.
- poll(time, unit) It will retrieve and removes the head of the queue, in case Queue is empty will wait until the specified time exhausted
Examine Operation
- element() :-It will retrieve and will not remove the head of the queue, in case Queue is empty will lead to an exception
- peek():- It will retrieve and will not remove the head of the queue, in case Queue is empty returns null.
ArrayBlockingQueue Example
import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class ArrayBlockingQueueExample { public static void main(String[] args) throws InterruptedException { List stringList=new ArrayList(); stringList.add("ArrayBlockingQueue"); stringList.add("example"); stringList.add("In"); stringList.add("Java"); BlockingQueue blockingQueue=new ArrayBlockingQueue(4,true,stringList); System.out.println(blockingQueue); } }