Java ArrayBlockingQueue Example

By Arvind Rai, 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) 
Creates with fixed size for given capacity and default access policy.
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) 
Creates with fixed size for given capacity and specified access policy.
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) 
Creates with fixed size for given capacity, specified access policy and specified initial collection. The specified collection are added in queue in traversal order of collection iterator.
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) 
Suppose we have an ArrayBlockingQueue with size 2.
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(2);
abq.add("Mahesh");
abq.add("Suresh");
System.out.println(abq); 
Output
[Mahesh, Suresh] 
We can see that size is full. The 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"); 
Output
java.lang.IllegalStateException: Queue full 
put(e) : Inserts the specified element at the tail of the queue and wait for space to become available if the queue is full.
Find the method declaration.
void put(E e) throws InterruptedException 
Find the example.
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); 
Output
[Mahesh, Suresh]
[Suresh]
[Suresh, Chandra] 
The size of the queue is 2. The line 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) 
Find the example.
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] 
offer(e, time, unit) : Inserts the specified element at the tail of the queue. If the queue is full, method waits for the specified time to become space available. If element is inserted, method returns true and if element could not be inserted within the specified time, method returns false .

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) 
Example
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] 
removeIf(Predicate<? super E> filter) : Removes all of the elements of this queue that satisfy the given predicate.
Find the method declarations.
boolean removeIf(Predicate<? super E> filter) 
Example
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); 
Output
[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 
Example
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); // [] 
poll() : Retrieves and removes the head of the queue. If the queue is empty, this method returns null.
Find the method declaration.
E poll() 
Example
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 
poll(time, unit) : Retrieves and removes the head of the queue. If the queue is empty, this method waits for the specified time for an element to become available.
Find the method declaration.
E poll(long timeout, TimeUnit unit) throws InterruptedException 
Example
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() 
Example
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) 
Example
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] 
clear() : Removes all elements of the queue.
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) 
Example
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(2);
abq.put("Mahesh");
abq.put("Suresh");
abq.forEach(s -> System.out.println(s)); 
Output
Mahesh
Suresh 

Reference

Class ArrayBlockingQueue
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us