Java Reference
In-Depth Information
SynchronousQueue : It is a special type of implementation of BlockingQueue . It does not have
any capacity. The put operation waits for the take operation to take the element being put.
It facilitates a kind of handshake between two threads. One thread tries to put an element
to the blocking queue that must wait until there is a thread that tries to take the element. It
facilitates an exchange of an object between two threads. You can also specify the fairness rule
for the queue. For all practical purposes, this blocking queue is always empty. It seems to have
an element only when there are two threads: one trying to add an element and one trying to
remove an element. Its isEmpty() method always returns true .
DelayQueue : It is another unbounded implementation class for BlockingQueue . It allows
an element to be taken out only if a specified delay has passed for that element. If there are
multiple elements in the blocking queue whose specified delay has passed, the element whose
delay passed earliest will be placed at the head of the blocking queue.
Let's start with an example of a producer/consumer application. Listing 12-21 has the code for a producer. It
accepts a blocking queue and a producer name in its constructor. It generates a string and adds it to the blocking
queue after waiting for a random number of seconds between 1 and 5. If the blocking queue is full, it will wait until the
space is available in the queue.
Listing 12-21. The Producer Class for a Blocking Queue
// BQProducer.java
package com.jdojo.collections;
import java.util.concurrent.BlockingQueue;
import java.util.Random;
public class BQProducer extends Thread {
private final BlockingQueue<String> queue;
private final String name;
private int nextNumber = 1;
private final Random random = new Random();
public BQProducer(BlockingQueue<String> queue, String name) {
this.queue = queue;
this.name = name;
}
@Override
public void run() {
while (true) {
try {
String str = name + "-" + nextNumber;
System.out.println(name + " is trying to add: " +
str + ". Remaining capacity: " +
queue.remainingCapacity());
this.queue.put(str);
nextNumber++;
System.out.println(name + " added: " + str);
// Sleep between 1 and 5 seconds
int sleepTime = (random.nextInt(5) + 1) * 1000;
Thread.sleep(sleepTime);
}
 
Search WWH ::




Custom Search