Java ArrayBlockingQueue Example
June 26, 2022
On this page we will learn using Java ArrayBlockingQueue
class.
1. The
ArrayBlockingQueue
is a bounded BlockingQueue
backed by an array. The BlockingQueue
is a Queue
of such type that while retrieving data, if queue is empty, it waits for an element to be available and while adding data, if there is no space, it waits for space to be available. The Queue
orders elements in FIFO (first-in-first-out).
2. A queue inserts elements at the tail and retrieves elements from the head. A tail in the queue is the element that has been on the queue for the shortest time. The head in the queue is that element that has been on the queue for the longest time.
3. The
ArrayBlockingQueue
is a fixed size array that cannot change its capacity after creation. If we try to put an element in the full queue, it will result in operation blocking. If we try to take an element from empty queue, it will also result in operation blocking.
4. The requests which are in waiting state, because of full and empty queue, are not necessarily in order by default. While constructing
ArrayBlockingQueue
by setting fairness to true, we can order the waiting requests in FIFO. Setting fairness to true generally decreases throughput but reduces variability and avoids starvation.
Constructors Summary
1.ArrayBlockingQueue(int capacity)
The default access policy means the threads that are blocked for putting or fetching elements may not be in order.
It throws
IllegalArgumentException
if capacity < 1.
2.
ArrayBlockingQueue(int capacity, boolean fair)
If the value for fair is true, the blocked requests for putting and fetching elements are ordered in FIFO (first-in-first-out).
It throws
IllegalArgumentException
if capacity < 1.
3.
ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c)
It throws
IllegalArgumentException
if capacity < 1 or < c.size() .
Methods for Insert
add(e) : Inserts the specified element at the tail of the queue only if space is available and returns true. If there is no space,IllegalStateException
is thrown. This method does not wait for space to be available.
Find the method declaration.
boolean add(E e)
ArrayBlockingQueue
with size 2.
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(2); abq.add("Mahesh"); abq.add("Suresh"); System.out.println(abq);
[Mahesh, Suresh]
ArrayBlockingQueue
is of fixed size with given capacity. Here is the size 2. Now if we try to add element, then add()
method will throw exception.
abq.add("Chandra");
java.lang.IllegalStateException: Queue full
Find the method declaration.
void put(E e) throws InterruptedException
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(2); abq.put("Mahesh"); abq.put("Suresh"); System.out.println(abq); Runnable task = () -> { abq.remove(); System.out.println(abq); }; ExecutorService e = Executors.newFixedThreadPool(1); e.submit(task); abq.put("Chandra"); System.out.println(abq);
[Mahesh, Suresh] [Suresh] [Suresh, Chandra]
abq.put("Chandra")
will wait for space to be available. Another thread is removing an element and after that new element is being added by main thread.
offer(e) : Inserts the specified element at the tail of the queue. If the queue is full, element is not inserted and method returns false. If space is available in queue, element is inserted and method returns true.
Find the method declaration.
boolean offer(E e)
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(2); boolean r1 = abq.offer("Mahesh"); // true System.out.println(r1); boolean r2 = abq.offer("Suresh"); // true System.out.println(r2); System.out.println(abq); // [Mahesh, Suresh] boolean r3 = abq.offer("Chandra"); System.out.println(r3); // false System.out.println(abq); // [Mahesh, Suresh]
Methods for Remove
remove(Object o) : Removes a single instance of the specified element from this queue, if it is present.Find the method declaration.
boolean remove(Object o)
abq.put("Mahesh"); abq.put("Suresh"); System.out.println(abq); // [Mahesh, Suresh] System.out.println(abq.remove("Mahesh")); // true System.out.println(abq.remove("Shiva")); // false System.out.println(abq); // [Suresh]
Find the method declarations.
boolean removeIf(Predicate<? super E> filter)
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(3); abq.put("Mahesh"); abq.put("Suresh"); abq.put("Shiva"); System.out.println(abq); abq.removeIf(s -> s.startsWith("S")); System.out.println(abq);
[Mahesh, Suresh, Shiva] [Mahesh]
removeAll(Collection<?> c) : Removes all the elements from the queue that matches the specified collection.
take() : Retrieves and removes the head of the queue. If the queue is empty, this method waits for an element to be available.
Find the method declaration.
E take() throws InterruptedException
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(2); Runnable task = () -> { abq.add("Shiva"); }; ExecutorService e = Executors.newFixedThreadPool(1); e.submit(task); abq.take(); System.out.println(abq); // []
Find the method declaration.
E poll()
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(2); abq.put("Mahesh"); abq.put("Suresh"); System.out.println(abq.poll()); // Mahesh System.out.println(abq.poll()); // Suresh System.out.println(abq); // [] System.out.println(abq.poll()); // null
Find the method declaration.
E poll(long timeout, TimeUnit unit) throws InterruptedException
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(2); Runnable task = () -> { try { Thread.sleep(1000); abq.add("Mahesh"); } catch (InterruptedException e1) { e1.printStackTrace(); } }; ExecutorService e = Executors.newFixedThreadPool(1); e.submit(task); String s = abq.poll(2000, TimeUnit.MILLISECONDS); System.out.println(s); // Mahesh
Methods for Examine
element() : Retrieves, but does not remove the element. If queue is empty, it throws exception.peek() : Retrieves, but does not remove the element. If queue is empty, it returns null.
Find the method declaration.
E peek()
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(2); abq.put("Mahesh"); abq.put("Suresh"); String s = abq.peek(); System.out.println(s); // Mahesh
Some other methods
drainTo(Collection<? super E> c) : Removes all available elements from this queue and adds them to the given collection.drainTo(Collection<? super E> c, int maxElements) : Removes at most the given number of available elements from this queue and adds them to the given collection.
Find the method declaration.
int drainTo(Collection<? super E> c, int maxElements)
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(3); abq.put("Mahesh"); abq.put("Suresh"); abq.put("Ramesh"); List<String> list = new ArrayList<>(); abq.drainTo(list, 2); System.out.println(list); // [Mahesh, Suresh] System.out.println(abq); // [Ramesh]
toArray() : Returns an array containing all the elements of the queue.
contains(Object o): Returns true if this queue contains the specified element.
forEach(Consumer<? super E> action) : Iterates the queue and performs the given action for each element.
Find the method declaration.
void forEach(Consumer<? super E> action)
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(2); abq.put("Mahesh"); abq.put("Suresh"); abq.forEach(s -> System.out.println(s));
Mahesh Suresh