What is the ArrayBlockingQueue.clear method in Java?
ArrayBlockingQueueis a bounded, thread-safe queue. Internally,ArrayBlockingQueueuses 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-Out Elements are inserted at the end of the queue and retrieved from the head of the queue nullobjects 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
ArrayBlockingQueuefrom thejava.util.concurrentpackage. -
Line 4: Create an object for the
ArrayBlockingQueueclass with the namequeueand size 5. -
Lines 5 to 7: Add three elements to the
queueobject. -
Line 10: Call the
clearmethod of thequeueobject. This will remove all the elements from thequeueand make thequeueempty.