Friday, January 20, 2012

Template: Multithreading solution using Executors

TEMPLATE: Thread Executors

Solution 1: No wait.

This is simple template to run multithreaded solution, where you don't need to wait for responses.


       public void start() {
              ExecutorService executor = Executors
                           .newFixedThreadPool(CONCURRENT_THREADS);

              for (int i = 0; i < NUMBER_OF_TASKS; i++) {
                     executor.submit(new SingleWorker(i));
              }
             
              executor.shutdown();
       }


Solution 2: Summary

When you need to for example summarise output of all threads, and do something with them I usually use List of Future 

       public void start() {
              ExecutorService executor = Executors
                           .newFixedThreadPool(CONCURRENT_THREADS);
             
              //list will kept information about threads status
              List<Future<Long>> list = new ArrayList<Future<Long>>();
             
              for (int i = 0; i < NUMBER_OF_TASKS; i++) {
                     Callable<Long> worker = new SingleWorker(i);
                     Future<Long> submit = executor.submit(worker);
                     list.add(submit);
              }
             
              // now retrieve the result
              for (Future<Long> future : list) {
                     try {
                           //get() is waiting for each thread to finish
                           future.get();
                     } catch (InterruptedException e) {
                           e.printStackTrace();
                     } catch (ExecutionException e) {
                           e.printStackTrace();
                     }
              }
              executor.shutdown();
              // at this point all threads are finish
              // add summary calculations
       }

Note: This is 2010 solution with java 1.6.