Parallel { public static <T,F> void For(final Collection<T> pElements, final Operation<T> pOperation) { forPool = Executors.newFixedThreadPool(poolSize); List<Future<?>> futures = new LinkedList<Future<?>>(); List<Pair<Integer,T>> indexedElements = new ArrayList<Pair<Integer,T>>(pElements.size()); int index = 0; for(final T element : pElements) { indexedElements.add( new Pair<Integer,T>(index,element) ); index++; } int size = index; for (final Pair<Integer,T> element : indexedElements) { try{ Future<?> future = forPool.submit(new Runnable() { @Override public void run() { pOperation.perform(element.getFirst(), element.getSecond()); } }); futures.add(future); } catch(Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } } int numComplete = 0; for (Future<?> f : futures) { try { f.get(); numComplete++; if (numComplete % 5000 == 0) System.out.printf ("."); } catch (InterruptedException e) { System.err.println(e.getMessage()); } catch (ExecutionException e) { System.err.println(e.getMessage()); } catch (Exception e) { System.err.println(e.getMessage()); } } if (size > 5000) System.out.printf ("\n"); forPool.shutdown(); }  static void setPoolSize(int poolSize); static void For(final Collection<T> pElements, final Operation<T> pOperation); void shutdown();  }
@Test public void test () { Random rgen = new Random(); int HK = 1000000; List<Short> array = new ArrayList<Short>(HK); long expTotal = 0; for (int i=0; i<HK; i++) { array.add((short) (rgen.nextInt() % Short.MAX_VALUE)); expTotal += array.get(i); } long startTime = System.currentTimeMillis(); long endTime; try { sum = 0; final Lock lock = new ReentrantLock(); Parallel.For(array, new Parallel.Operation<Short>() { @Override public void perform(int index, Short pParameter) { lock.lock(); sum += pParameter; lock.unlock(); } }); } finally { endTime = System.currentTimeMillis(); } long duration = endTime - startTime; System.out.println ("Parallel took " + duration+ " milliseconds"); assertTrue(sum == expTotal); startTime = System.currentTimeMillis(); ReducibleTotaller mrt = new ReducibleTotaller(); try { mrt = ThreadPool.mapReduce (array, mrt, new ThreadPool.Operation<ReducibleTotaller,Short>() { public void perform(ReducibleTotaller tot, int index, Short val) { tot.add(val); } }); } finally { endTime = System.currentTimeMillis(); } duration = endTime - startTime; System.out.println ("Mapreduce took " + duration+ " milliseconds"); assertTrue(mrt.sum == expTotal); }