Wednesday, October 10, 2012

Java Concurrency / Multithreading: Part 3

In Previous post (Java Concurrency / Multithreading :Part 2) learn how to initialize and use ExecutorService.

There are numerous problem domains where while designing the application you will need to implement the thread pool and each thread after completing the task, based on inputs should return a value. Futures and Callables exist exactly to solve this area.

Till now we have implemented the thread pool (in previous post) using the Runnables which do not return any value. In case a thread should return a value based on computation or work done as part of task you can use java.util.concurremt.Callable. Callable return value after execution. Callable returns an object of java.util.concurrent.Future. Future is used to check the status of task and return some value. Below is the example to use Callable and return a value

public class MyRunnable implements Callable<Long> {  
     @Override  
     public Long call() throw Exception {  
       return 5L;  
     }  
   } 

Using the Executor Framework

public class Example {

    public static void main(String[] args) {



        ExecutorService executor = Executors.newFixedThreadPool(5);

        List<Future<Long>> fList = new ArrayList<Future<Long>>();

        for (int i = 0; i < 999; i++) {

            Callable<Long> worker = new MyRunnable();

            Future<Long> submit = executor.submit(worker);

            fList.add(submit);

        }

        long sum = 0;



        for (Future<Long> future : fList) {

            try {

            sum += future.get();

            } catch (InterruptedException e) {

            e.printStackTrace();

            } catch (ExecutionException e) {

            e.printStackTrace();

            }

        }

        System.out.println("Final Sum is : " + sum);

        executor.shutdown();

    }

} 

No comments:

Post a Comment