LinkedBlockingQueue in Java
LinkedBlockingQueue is an implementation of the BlockingQueue, Which is backed by the Linked Node Data Structure. LinkedBlockingQueue can be initialized with and without the specified limit.
Specified limit should be with in the limit of primitive data type int , the following are constructors of the LinkedBlockingQueue.
- LinkedBlockingQueue (int capacity)
- LinkedBlockingQueue(Collection<? extends E> c)
capacity is the limit in terms of how many elements can be inserted in LinkedBlockingQueue at max, Collection is the list of elements which needs to be inserted into the queue at the time of initialization. And queue will be accessed in the terms of FIFO no need of any other parameters like ArrayBlockingQueue.
This Collection size should be less than the capacity of the LinkedBlockingQueue otherwise this will lead to an java.lang.IllegalStateException
The following are the most commonly used methods in the LinkedBlockingQueue.
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(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
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.
LinkedBlockingQueue Example in Java