|
Concurrent Collections
in Java |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
size(),
isEmpty()) since all of the locks would have to
be acquired
ConcurrentHashMap
ConcurrentModificationException
ConcurrentHashMap (cont.)LinkedBlockingQueue
BlockingQueue
interface):
| Throws Exception | Returns Special | Blocks Until | Times Out | |
| Insert |
add(e)
|
offer(e)
|
put(e)
|
offer(e, time, timeunit)
|
| Remove |
remove()
|
poll()
|
take()
|
poll(time, timeunit)
|
| Examine |
element()
|
peek()
|
|
|
LinkedBlockingQueue
Dispatcher is used by
a DailyDispatchHandler and
a RealTimeDispatchHandler, each of which
executes in its own threaddispatch() method
enters the waiting state if no vehicles are
availablemakeVehicleAvailable() notifies the waiting
threadsDispatcher uses
a LinkedBlockingQueue
import java.util.concurrent.*;
/**
* Used to dispatch vehicles in a fleet (e.g., emergency
* response vehicles).
*
* This version uses a LinkedBlockingQueue
*
* @author Prof. David Bernstein, James Madison University
* @version 6.0b
*/
public class Dispatcher
{
protected int numberOfVehicles;
protected LinkedBlockingQueue<Integer> availableVehicles;
/**
* Construct a new Dispatcher
*
* @param n The number of vehicles in the fleet
*/
public Dispatcher(int n)
{
int i;
numberOfVehicles = n;
availableVehicles = new LinkedBlockingQueue<Integer>();
for (i=0; i < n; i++)
{
makeVehicleAvailable(i);
}
}
/**
* Dispatch an available vehicle
*
* @param task The task to be handled
* @return true if a vehicle was dispatched
*/
public boolean dispatch(String task)
{
int vehicle;
Integer v;
v = availableVehicles.take(); // Wait if necessary
vehicle = v.intValue();
sendMessage(vehicle, task);
return true;
}
/**
* Makes a vehicle available for future dispatching
*
* @param vehicle The number of the vehicle
*/
public void makeVehicleAvailable(int vehicle)
{
availableVehicles.put(new Integer(vehicle));
}
/**
* Sends a message to a vehicle
*
* @param vehicle The number of the vehicle
* @param message The message to send
*/
private void sendMessage(int vehicle, String message)
{
// This method would normally transmit the message
// to the vehicle. For simplicity, it now writes it
// to the screen instead.
System.out.println(vehicle+"\t"+message+"\n");
System.out.flush();
}
}
ArrayBlockingQueue
:
LinkedBlockingDeque
(pronounced like "deck"):
PriorityBlockingQueue