JMU
Concurrent Collections
in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Concurrent Collections
Copy-on-Write Collections
Compare-and-Swap Collections
Fine-Grained-Lock Collections
FGL (cont.) - ConcurrentHashMap
FGL (cont.) - ConcurrentHashMap (cont.)
FGL (cont.) - LinkedBlockingQueue
GLF (cont.) An Example of a LinkedBlockingQueue
An Example (cont.)
javaexamples/threads/v6b/Dispatcher.java
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();       
    }
}
        
FGL (cont.) - Other Classes