Wednesday, October 10, 2012

Java Concurrency / Multithreading: Part 2

See my earlier post (Java Concurrency / Multithreading :Part 1) related to basics about java threads and concurrency.

Executor Framework

ThreadPools is the way to manage the pool of working threads and limit the creation of thread as creating a thread have resource overhead associates with it. Thus thread pools contains a work queue waiting for their turn to get executed.

In thread pool, the thread are constantly running and checking the queue for new work. As soon as the pool have a idle thread the work is assigned to one of the threads.

With Java 5 came Executor Framework under java.util.concurrent package, so that you do not need to create and manage your own pool e.g java.util.concurrent.Executor can be initialized as Executors.newfixedThreadPool(n) to create n worker threads. 

Like wise Executors.newSingleThreadExecutor(); will create a single thread pool with only one worker thread.

Example:
Creating a Runnable class
public class MyRunnable implements Runnable {
    private final long count;
    MyRunnable(long count) {
        this.count = count;
    }
    @Override
    public void run() {
        long mySum = 0;
        for (long i = 1; i < count; i++) {
            mySum = mySum + i;
        }
        System.out.println(mySum);
    }
}

Using the Executor Framework
public class Example {

    public static void main(String[] args) {

        ExecutorService executor = Executors.newFixedThreadPool(5);

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

            Runnable myworker = new MyRunnable(99999999L + i);

            executor.execute(myworker);

        }

        executor.shutdown();

        while (!executor.isTerminated()) {



        }

        System.out.println("Completed processing the work queue");

    }

} 


ExecutorService executor = Executors.newFixedThreadPool(5); creates a new pool of 5 worker threads.

executor.execute(myworker); adds new work in the queue for thread pool to complete.

executor.shutdown(); waits till all the work in the queue is completed. After calling this method the ExecutorService will not take any new task but once all the current tasks in the queue are complete the ExecutorService will shutdown.

To stop the ExecutorService immediately call shutdownNow() method.This will attempt to stop all executing tasks right away, and skips all submitted but non-processed tasks. There are no guarantees given about the executing tasks. Perhaps they stop, perhaps the execute until the end. It is a best effort attempt.

 executor.isTerminated() checks if the service is terminated or not.

Till now we have submitted the tasks to ExecutorService and never waited to get a return value after . Thus in case the threads should return some value then you should use java.util.concurrent.Callable. See my next post (Java Concurrency / Multithreading: Part 3) summarizing the above concept.

No comments:

Post a Comment