Sunday, November 27, 2011

What is an Executor?

An executor is an object that can start and manage threads. This can make thread programming much easier and more efficient. An executor can execute a Runnable task a Callable task. The java.util.concurrent.Executors class provides static factory methods for creating executor objects. You can create an ExecutorService object like this:

ExecutorService threadPool = Executors.newCachedThreadPool();

This creates an object that creates new threads as required. Each time you use the threadPool object to start another task, either an existing thread in the pool that is currently no longer running is used, or a new thread is created and added to the thread pool. If you want to limit the number of threads that might be created, you can create a thread pool with a fixed number of threads, like this:

int totalThreads = 5;
ExecutorService threadPool = Executors.newFixedThreadPool(totalThreads);

This fragment creates a thread pool that contains up to totalThreads threads. Starting a new task using the threadPool object results in the task being executed in a new thread as long as there are fewer than totalThreads threads already in operation. If all threads in the pool have been allocated, the new task is placed in a queue to wait until one of the existing threads becomes free. All the threads in the pool continue to exist until threadPool is shut down. The method throws an exception of type IllegalArgumentException if you specify the maximum number of threads to be less than 1.

No comments: