Monday, February 22, 2010

Blocking Queue Sample

import java.util.*;
import java.util.concurrent.*;
import java.io.*;


public class BlockingQueue {
    private static List waitingCustomerList = null;
    private static final String filePath = "/home/serkans/phoneNumbersOnly.txt";
    private static ArrayBlockingQueue waitingCustomersQueue = null;


    public static void main (String[] args)  {


        loadNumbers();


        initializeBlockingQueue();


        Runnable callcenterGirl = new Runnable (){
            public void run () {
                while (true) {


                 String phoneNumber = null;
                 try {
                     phoneNumber = waitingCustomersQueue.poll (10000L, TimeUnit.MILLISECONDS);
                     if (null != phoneNumber){
                         System.out.println (" -- Callcenter girl is helping to : " + phoneNumber);
                     }else{
                         System.out.println ( " -- Callcenter girl is waiting  : " + phoneNumber);
                     }
                 } catch (InterruptedException ex) {
                     System.out.println ("  -- Callcenter girl is interrupted ex:");
                     ex.printStackTrace();
                 }
             }


         }
        };


        Thread t = new Thread (callcenterGirl);
        t.start();




    }


    private static ArrayBlockingQueue initializeBlockingQueue () {
        try {
            waitingCustomersQueue = new ArrayBlockingQueue(waitingCustomerList.size (), true, waitingCustomerList);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(1);
        }
        return waitingCustomersQueue;
    }


    private static void loadNumbers () {
        Properties props = new Properties();
        try {
            props.load (new FileInputStream (new File (filePath)));
            System.out.println (" -- item count in file is :" + props.size());
            waitingCustomerList = new ArrayList (props.keySet());
        } catch (IOException ex) {
            System.out.println (" -- Unable to find file : "+filePath);
        }
    }
}

No comments:

Post a Comment