Saturday, August 29, 2009

ThreadPool in Java

Thread pools address two different problems.
  1. They usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead.
  2. They provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks.
Lets look at simple program which gives better understanding of how ThreadPool works in Java.


class Workers implements Runnable {
private final int value;
Workers(int value) {
this.value = value;
}
public void run() {
System.out.println("Value = " + value);
}
}

public class ThreadPoolExample {
public static void main(String[] args) {
// The Executors class provides factory methods for the executor services provided
// by java.util package.
// newFixThreadPool creates a thread pool that reuses a fixed set of threads
// operating off a shared unbounded queue. If any thread terminates due to
// a failure during execution prior to shutdown, a new one will take its place
// if needed to execute subsequent tasks.
ExecutorService executors = Executors.newFixedThreadPool(5);

for (int i = 0; i < 10; i++) {
// Submits a Runnable task for execution and returns a Future
// representing that task.
executors.submit(new Workers(i));
}

// An ExecutorService can be shut down, which will cause it to stop
// accepting new tasks. After being shut down, the executor will
// eventually terminate, at which point no tasks are actively executing,
// no tasks are awaiting execution, and no new tasks can be submitted.
executors.shutdown();
try {
// Blocks until all tasks have completed execution after a shutdown request,
// or the timeout occurs, or the current thread is interrupted, whichever
// happens first.
executors.awaitTermination(1000, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Result of the program might differ from this result.
Value = 0
Value = 2
Value = 3
Value = 4
Value = 5
Value = 7
Value = 8
Value = 9
Value = 1
Value = 6

No comments: