Created
July 5, 2024 05:12
The dequeue methods of Blocking Queue which are used to retrieve and remove elements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.BlockingQueue; | |
import java.util.concurrent.LinkedBlockingQueue; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* The dequeue methods of Blocking Queue which are used to retrieve and remove | |
* elements. | |
*/ | |
public class DequeueMethodsBQ { | |
public static void main(String[] args) { | |
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(); | |
/** | |
* Take method retrieves and removes the head of the queue, waiting if necessary | |
* until an element becomes available. This method blocks the thread if the | |
* queue is empty, waiting indefinitely until an element is available to be | |
* retrieved. | |
*/ | |
try { | |
Integer element = queue.take(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
/** | |
* poll method retrieves and removes the head of the queue, returning null if | |
* the queue is empty. Unlike take(), poll() does not block the thread | |
* indefinitely if the queue is empty. It returns null immediately if no element | |
* is available. | |
*/ | |
Integer element = queue.poll(); | |
/** | |
* This version of poll method retrieves and removes the head of the queue, | |
* waiting up to the specified wait time if necessary for an element to become | |
* available. Returns null if the specified waiting time elapses before an | |
* element is available. | |
*/ | |
try { | |
Integer element1 = queue.poll(10, TimeUnit.SECONDS); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
// removes if the object is present. | |
boolean wasRemoved = queue.remove(1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment