harin
3/22/2013 - 2:56 PM

hw7again.java

import java.util.ArrayList;
import java.util.*;
import java.util.concurrent.*;

public class AlienCommHopefullyCorrect {
  
    public static void main(String[] args)
    {
    	int NUM_THREADS = 4;
    	ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
    	
    	final long start = System.nanoTime();
        try {
            System.out.println("Initiaing communication system...");

            int i = 0;
            while(AlienLib.isAlienTransmitting())
            {
            	//STAGE 1 - get the signals into arrayList
                ArrayList<AlienLib.Garble> signals = AlienLib.getAlienSignals();
                
                //STAGE 2 - divide the work and process
                int dataSize = signals.size();
                int partitionSize = dataSize/ NUM_THREADS;

                List<SignalTaskExecutor> workers = new LinkedList<SignalTaskExecutor>();
                for(int j = 0; j < NUM_THREADS; j++)
                {
                    final int from = j * partitionSize;
                    final int to   = from + partitionSize;

                    workers.add( new SignalTaskExecutor(signals, from, to) );
                }
                
                List<Future<ArrayList<AlienLib.Data>>> results = executor.invokeAll(workers);
                
                //STAGE 3 - retrieve data from worker
                ArrayList<AlienLib.Data> data = new ArrayList<AlienLib.Data>();
                for(Future<ArrayList<AlienLib.Data>> result: results){
                	data.addAll(result.get());
                }
                
                AlienLib.transmitToPrimeMinisterOffice(data);

                System.out.println("Pass: "+ i++ +" with "+ data.size()+" signals.");
            }

            System.out.println("Done processing alien's data.");
            
            final long end = System.nanoTime();
        	System.out.println("Time taken: "+(end-start)/1.0e6);
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    //change Garble to Data 
    // return ArrayList of AlienLib.Data
    // 
    public static class SignalTaskExecutor implements Callable<ArrayList<AlienLib.Data>> {
        private ArrayList<AlienLib.Garble> data;
        private int from;
        private int to;

        SignalTaskExecutor(ArrayList<AlienLib.Garble> data, int from, int to) {
            this.data = data;
            this.from = from;
            this.to = to;
        }

        @Override
        public ArrayList<AlienLib.Data> call() throws Exception{
            ArrayList<AlienLib.Data> result = new ArrayList<AlienLib.Data>();

            for (int i = from; i < to; i++) {
                result.add(AlienLib.processAlienSignal(data.get(i)));
            }

            return result;
        }
    }
}