Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
ArrayBlockingQueue add() method in Java
Next article icon

ArrayBlockingQueue Class in Java

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the ArrayBlockingQueue class is part of the java.util.concurrent package and implements the BlockingQueue interface. It is a thread-safe, bounded queue that helps manage producer-consumer scenarios by blocking threads when the queue is full or empty.

  • The queue has a fixed size, specified during creation.
  • Methods like take() and put() block the calling thread when the queue is full or empty
  • It is safe for use in multi-threaded environments without needing additional synchronization.

Example: This example demonstrates how to use ArrayBlockingQueue with a fixed capacity, blocking if the queue is full.

Java
// Java Program to demonstrates  // the working of ArrayBlockingQueue import java.util.concurrent.ArrayBlockingQueue;  public class Geeks {     public static void main(String[] args)         throws InterruptedException     {          // Create an ArrayBlockingQueue          // with a capacity of 3         ArrayBlockingQueue<Integer> q             = new ArrayBlockingQueue<>(3);          // Adding elements to the queue         q.put(1);         q.put(2);         q.put(3);          // Print the queue after adding elements         System.out.println("Queue after adding elements: "                            + q);     } } 

Output
Queue after adding elements: [1, 2, 3] 


ArrayBlockingQueue Hierarchy

The below diagram demonstrates the class hierarchy for ArrayBlockingQueue and LinkedListBlockingQueue, both implementing the BlockingQueue interface, which extends Queue, Collection, and Iterable

ArrayBlockingQueue-Class-in-Java


Declaration of ArrayBlockingQueue

In Java, the declaration of ArrayBlockingQueue can be done as:

ArrayBlockingQueue<Type> queue = new ArrayBlockingQueue<>(capacity)

Note: Here Type is the type of element the queue will hold (e.g Integer, String) and capacity is the maximum number of elements the queue can hold.

Constructors

Constructor

Description

ArrayBlockingQueue(int capacity)

Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy. 

ArrayBlockingQueue(int capacity, boolean fair)

reates a queue with the specified capacity and a fair or non-fair locking policy based on the fair argument.

ArrayBlockingQueue(int capacity, boolean fair, Collection c)

Creates a queue with the specified capacity, locking policy, and initializes it with elements from the given collection


Example: This example demonstrates the creation of an ArrayBlockingQueue with a specified capacity and adding elements to it.

Java
// Java program to demonstrate the working of // ArrayBlockingQueue(int initialCapacity) // constructor import java.util.concurrent.ArrayBlockingQueue;  public class Geeks {      public static void main(String[] args)     {         // define capacity of ArrayBlockingQueue         int c = 15;          // create object of ArrayBlockingQueue         // using ArrayBlockingQueue(int initialCapacity) constructor         ArrayBlockingQueue<Integer> a = new ArrayBlockingQueue<Integer>(c);          // add numbers         a.add(1);         a.add(2);         a.add(3);          // print queue         System.out.println("ArrayBlockingQueue:" + a);     } } 

Output
ArrayBlockingQueue:[1, 2, 3] 

Performing Various Operations on ArrayBlockingQueue

1. Adding Elements: We use add() method to insert elements into an ArrayBlockingQueue.

Example: This example demonstrates how to create and add elements to an ArrayBlockingQueue.

Java
// Adding elements to an ArrayBlockingQueue import java.util.concurrent.ArrayBlockingQueue;  public class Geeks {      public static void main(String[] args)     {         // define capacity of ArrayBlockingQueue         int c = 15;          // create object of ArrayBlockingQueue         ArrayBlockingQueue<Integer> a             = new ArrayBlockingQueue<Integer>(c);          // add numbers         a.add(100);         a.add(200);         a.add(300);          // print queue         System.out.println("ArrayBlockingQueue : " + a);     } } 

Output
ArrayBlockingQueue : [100, 200, 300] 


2. Removing Elements: We can use remove() method to remove elements from the ArrayBlockingQueue.

Example: This example demonstrates how to remove a specific element from an ArrayBlockingQueue.

Java
// Remove elements from an ArrayBlockingQueue import java.util.concurrent.ArrayBlockingQueue; public class Geeks{      public static void main(String[] args)     {         // define capacity of ArrayBlockingQueue         int c = 15;          // create object of ArrayBlockingQueue         ArrayBlockingQueue<Integer> a = new ArrayBlockingQueue<Integer>(c);          // add numbers         a.add(1);         a.add(2);         a.add(3);          // print queue         System.out.println("ArrayBlockingQueue: " + a);          // remove 223         boolean b = a.remove(2);          // print Queue         System.out.println("Element 2 removed ?: " + b);          // print Queue         System.out.println("Updated ArrayBlockingQueue: " + a);              } } 

Output
ArrayBlockingQueue: [1, 2, 3] Element 2 removed ?: true Updated ArrayBlockingQueue: [1, 3] 


3. Accessing Elements: We can use the peek() method to retrieve the head of the queue without removing it.

Example: This example demonstrates how to retrieve the head of the queue using the peek() method.

Java
// Accessing elements in an ArrayBlockingQueue import java.util.concurrent.ArrayBlockingQueue; public class Geeks{      public static void main(String[] args)     {         // Define capacity of ArrayBlockingQueue         int c = 5;          // Create object of ArrayBlockingQueue         ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<Integer>(c);          // Add element to ArrayBlockingQueue         q.add(23);         q.add(32);         q.add(45);         q.add(12);          // Print queue          System.out.println("ArrayBlockingQueue is: " + q);          // Print head of queue using peek() method         System.out.println("Head of queue is: " + q.peek());     } } 

Output
ArrayBlockingQueue is: [23, 32, 45, 12] Head of queue is: 23 


4. Iterating Elements: We use iterator() method to iterate over the elements of an ArrayBlockingQueue in the order from head to tail.

Example: This example demonstrates how to use the iterator() method to iterate over the elements of an ArrayBlockingQueue.

Java
// Iterating elements in an ArrayBlockingQueue import java.util.*; import java.util.concurrent.ArrayBlockingQueue;  public class Geeks {      public static void main(String[] args)     {         // Define capacity of ArrayBlockingQueue         int c = 5;          // Create object of ArrayBlockingQueue         ArrayBlockingQueue<String> q             = new ArrayBlockingQueue<String>(c);          // Add elements to ArrayBlockingQueue         q.offer("Java");         q.offer("C++");         q.offer("Python");         q.offer("Js");          // Print ArrayBlockingQueue         System.out.println("ArrayBlockingQueue is: " + q);          // Call iterator() method and Create an iterator         Iterator i = q.iterator();          // Print elements of iterator         System.out.println("The iterator values:");         while (i.hasNext()) {             System.out.print(i.next() + " ");         }     } } 

Output
ArrayBlockingQueue is: [Java, C++, Python, Js] The iterator values: Java C++ Python Js 

Methods

Methods

Description

add​(E e)Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and throwing an IllegalStateException if this queue is full.
clear()Atomically removes all of the elements from this queue.
contains​(Object o)Returns true if this queue contains the specified element.
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.
forEach​(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
iterator()Returns an iterator over the elements in this queue in the proper sequence.
offer​(E e)Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and false if this queue is full.
offer​(E e, long timeout, TimeUnit unit)Inserts the specified element at the tail of this queue, waiting up to the specified wait time for space to become available if the queue is full.
put​(E e)Inserts the specified element at the tail of this queue, waiting for space to become available if the queue is full.
remainingCapacity()Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking.
remove​(Object o)Removes a single instance of the specified element from this queue, if it is present.
removeAll​(Collection<?> c)Removes all of this collection's elements that are also contained in the specified collection (optional operation).
removeIf​(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
retainAll​(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
size()Returns the number of elements in this queue.
spliterator()Returns a Spliterator over the elements in this queue.
toArray()Returns an array containing all of the elements in this queue, in proper sequence.
toArray​(T[] a)Returns an array containing all of the elements in this queue, in proper sequence; the runtime type of the returned array is that of the specified array.

Methods Declared in Class java.util.AbstractQueue

Methods

Description

addAll​(Collection<? extends E> c)Adds all of the elements in the specified collection to this queue.
element()Retrieves, but does not remove, the head of this queue.
remove()Retrieves and removes the head of this queue.

Methods Declared in Class java.util.AbstractCollection

Methods

Description

containsAll​(Collection<?> c)Returns true if this collection contains all of the elements in the specified collection.
isEmpty()Returns true if this collection contains no elements.
toString()Returns a string representation of this collection.

Methods Declared in Interface java.util.concurrent.BlockingQueue

Methods

Description

poll​(long timeout, TimeUnit unit)Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available.
take()Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Methods Declared in Interface java.util.Collection

Methods

Description

addAll​(Collection<? extends E> c)Adds all of the elements in the specified collection to this collection (optional operation).
containsAll​(Collection<?> c)Returns true if this collection contains all of the elements in the specified collection.
equals​(Object o)Compares the specified object with this collection for equality.
hashCode()Returns the hash code value for this collection.
isEmpty()Returns true if this collection contains no elements.
parallelStream()Returns a possibly parallel Stream with this collection as its source.
stream()Returns a sequential Stream with this collection as its source.
toArray​(IntFunction<T[]> generator)Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

Methods Declared in Interface java.util.Queue

Methods

Description

element()Retrieves, but does not remove, the head of this queue.
peek()Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
poll()Retrieves and removes the head of this queue, or returns null if this queue is empty.
remove()Retrieves and removes the head of this queue.



Next Article
ArrayBlockingQueue add() method in Java

C

code_r
Improve
Article Tags :
  • Java
  • Java-Collections
  • Java - util package
  • Java-ArrayBlockingQueue
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

    ArrayBlockingQueue Class in Java
    In Java, the ArrayBlockingQueue class is part of the java.util.concurrent package and implements the BlockingQueue interface. It is a thread-safe, bounded queue that helps manage producer-consumer scenarios by blocking threads when the queue is full or empty.The queue has a fixed size, specified dur
    8 min read
    ArrayBlockingQueue add() method in Java
    ArrayBlockingQueue is bounded, blocking queue that stores the elements internally backed by an array. ArrayBlockingQueue class is a member of the Java Collections Framework. Bounded means it will have a fixed size, you can not store number the elements more than the capacity of the queue. The queue
    3 min read
    ArrayBlockingQueue clear() Method in Java
    ArrayBlockingQueue is bounded, blocking queue that stores the elements internally backed by an array. ArrayBlockingQueue class is a member of the Java Collections Framework.Bounded means it will have a fixed size, you can not store number the elements more than the capacity of the queue.The queue al
    2 min read
    ArrayBlockingQueue contains() method in Java
    ArrayBlockingQueue is bounded, blocking queue that stores the elements internally backed by an array. ArrayBlockingQueue class is a member of the Java Collections Framework. Bounded means it will have a fixed size, you can not store number the elements more than the capacity of the queue. The queue
    3 min read
    ArrayBlockingQueue drainTo() Method in Java
    ArrayBlockingQueue is bounded, blocking queue that stores the elements internally backed by an array. ArrayBlockingQueue class is a member of the Java Collections Framework.Bounded means it will have a fixed size, you can not store number the elements more than the capacity of the queue.The queue al
    5 min read
    ArrayBlockingQueue iterator() Method in Java
    The iterator() method of ArrayBlockingQueue class is used to returns an iterator of the same elements as this queue in a proper sequence. The elements returned from this method contains elements in order from first(head) to last(tail). The returned iterator is weakly consistent. Syntax: public Itera
    2 min read
    ArrayBlockingQueue offer() Method in Java
    ArrayBlockingQueue is bounded, blocking queue that stores the elements internally backed by an array. ArrayBlockingQueue class is a member of the Java Collections Framework. Bounded means it will have a fixed size, you can not store number the elements more than the capacity of the queue. The queue
    6 min read
    ArrayBlockingQueue peek() Method in Java
    ArrayBlockingQueue is bounded, blocking queue that stores the elements internally backed by an array. ArrayBlockingQueue class is a member of the Java Collections Framework.Bounded means it will have a fixed size, you can not store number the elements more than the capacity of the queue.The queue al
    2 min read
    ArrayBlockingQueue poll() Method in Java
    ArrayBlockingQueue is bounded, blocking queue that stores the elements internally backed by an array. ArrayBlockingQueue class is a member of the Java Collections Framework. Bounded means it will have a fixed size, you can not store number the elements more than the capacity of the queue. The queue
    4 min read
    ArrayBlockingQueue put() method in Java
    ArrayBlockingQueue is bounded, blocking queue that stores the elements internally backed by an array. ArrayBlockingQueue class is a member of the Java Collections Framework. Bounded means it will have a fixed size, you can not store number the elements more than the capacity of the queue. The queue
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences