Java Reference
In-Depth Information
Listing 12-25. Using a DelayQueue with Instances of DelayedJob as Its Element
// DelayQueueTest.java
package com.jdojo.collections;
import java.time.Instant;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
public class DelayQueueTest {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<DelayedJob> queue = new DelayQueue<>();
Instant now = Instant.now();
// Create three delayed job and add them to the queue
// Jobs should run in a sequence as
// 1. Populate Data (After 3 seeconds)
// 2. Balance Data (After 6 seconds)
// 3. Print Data (After 9 seconds)
queue.put(new DelayedJob("Print Data", now.plusSeconds(9)));
queue.put(new DelayedJob("Populate Data", now.plusSeconds(3)));
queue.put(new DelayedJob("Balance Data", now.plusSeconds(6)));
while (queue.size() > 0) {
System.out.println("Waiting to take a job from the queue...");
DelayedJob job = queue.take();
System.out.println("Took Job: " + job);
}
System.out.println("Finished running all jobs.");
}
}
Waiting to take a job from the queue...
Took Job: (Populate Data, Scheduled Time: 2014-05-09T02:35:44.721Z)
Waiting to take a job from the queue...
Took Job: (Balance Data, Scheduled Time: 2014-05-09T02:35:47.721Z)
Waiting to take a job from the queue...
Took Job: (Print Data, Scheduled Time: 2014-05-09T02:35:50.721Z)
Finished running all jobs.
Transfer Queues
The transfer queue extends the functionality of a blocking queue. An instance of the TransferQueue represents a
transfer queue. In a TransferQueue , a producer will wait to hand off an element to a consumer. This is a useful feature
in a message passing application, where a producer makes sure that its message has been consumed by a consumer.
A producer hands off an element to a consumer using the transfer(E element ) method of the TransferQueue .
When a producer invokes this method, it waits until a consumer takes its element. If the TransferQueue has some
elements, all its elements must be consumed before the element added by the transfer() method is consumed. The
tryTransfer() method provides a non-blocking and a timeout version of the method, which lets a producer transfer
an element immediately if a consumer is already waiting or wait for a specified amount of time.
 
Search WWH ::




Custom Search