Java Executor Service

The following code illustrates the usage of handling multiple threads using ExecutorService and Callable Interface.
The Callable Interface is similar to Runnable interface, except that it has following call() method instead of run().

 V call() throws Exception;

The major difference is call() method returns an object as a result of executing the thread and run() ( in Runnable Interface) method doesn't return.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class MyExecutorService {

        private static final int MAX_THREADS = 10;

        private static final int MAX_TIME_OUT = 5;

        public static void main(String[] args) {

                ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);
                List<Future<String>> list = new ArrayList<Future<String>>();
                for (int i = 0; i < 20; i++) {
                        Callable<String> worker = new MyCallableThread(
                                        new Integer(i).toString());
                        Future<String> submit = executor.submit(worker);
                        list.add(submit);
                }
                for (Future<String> future : list) {
                        try {
                                System.out.println(future.get(MAX_TIME_OUT, TimeUnit.SECONDS));
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        } catch (ExecutionException e) {
                                e.printStackTrace();
                        } catch (TimeoutException e) {
                                System.out.println("Thread TimeOut Exception Occured "
                                                + e.getMessage());
                        }
                }
                System.out.println("Shutting Down Executor");
                executor.shutdownNow();
        }
}

class MyCallableThread implements Callable<String> {

        private String name;

        MyCallableThread(String name) {
                this.name = name;
        }

        public String call() throws Exception {
                System.out.println("Thread " + name + ": Started ");

                if ((Integer.parseInt(name) % 2) == 0) {

                        Thread.sleep(100);
                } else
                        Thread.sleep(1000);

                System.out.println(name + " sleeping for " + name);

                return "Returned from " + name;
        }

}

Technology: 

Search