What is the ArrayBlockingQueue.clear method in Java?

ArrayBlockingQueue is a bounded, thread-safe queue. Internally, ArrayBlockingQueue uses a fixed-size array, meaning that once the object is created, the size cannot be changed. The elements of this queue follow First-In-First-OutElements are inserted at the end of the queue and retrieved from the head of the queue. null objects are not allowed as elements.

The clear method can be used to delete all the elements of the ArrayBlockingQueue object.

Syntax

public void clear()

Parameters

This method doesn’t take any arguments.

Return value

The clear() method doesn’t return a value.

Code

The code below demonstrates how to use the clear method.

import java.util.concurrent.ArrayBlockingQueue;
class Clear {
public static void main( String args[] ) {
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
queue.add("1");
queue.add("2");
queue.add("3");
System.out.println("The queue is " + queue);
queue.clear();
System.out.println("After calling the clear method the queue is " + queue);
}
}

Code explanation

  • Line 1: Import ArrayBlockingQueue from the java.util.concurrent package.

  • Line 4: Create an object for the ArrayBlockingQueue class with the name queue and size 5.

  • Lines 5 to 7: Add three elements to the queue object.

  • Line 10: Call the clear method of the queue object. This will remove all the elements from the queue and make the queue empty.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources