The Executor Framework has been introduced in Java 1.5 and it is a part of java.util.concurrent package. The Executor framework is an abstraction over the actual implementation of java multithreading. It is used for standardizing invocation, scheduling, execution and control of asynchronous tasks according to a set of execution policies defined during the creation of the constructor.
Before java 1.5, multithreading applications were created using thread group , thread pool or custom thread pool. Now the control of each thread has to be done by the programmer keeping in mind the following points
● Synchronization
● Locking
● Notification
● Dead lock
And many more that arises out of the application requirement. Some time it is very difficult to control multithreading applications because the behaviors of the threads are also dependent on the environment where the application is deployed and running. For example the processor speed, the RAM size, the band width all has a direct effect on the multithreading application. So you have to keep all these factors in mind before creating architecture.
An Executor framework provides multi-threading application programs with a easy abstraction for thinking about tasks. Instead of thinking in terms of threads, an application now deals simply with instances of Runnable (which is basically collections of tasks). And then it is passed to an Executor to process. The ExecutorService interface extends the simplistic Executor interface and there are life cycle methods to manage the executor framework.
The Executor framework represents tasks by using instances of Runnable or Callable. Runnable‘s run () method does not return a value or throw a checked exception. Callable is a more functional version in that area. It defines a call () method that allows the return of some computed value which can be used in future processing. And it also throws an exception if necessary.
The FutureTask class is used to get future information about the processing. An instance of this class can wrap either a Callable or a Runnable. You can get an instance of this as the return value of submit () method of an ExecutorService. You can also manually wrap your task in a FutureTask before calling execute () method.
Following are the function steps to implement the ThreadPoolExecutor.
● A pool of multiple/single thread is created.
● A queue is created holding all the tasks but these tasks are not yet assigned to threads from the pool. Bounded and unbounded queues are available.
● Rejection handler is used to handle the situation when one or more tasks are not able to assign in the queue. As per the default rejection policy, it will simply throw a RejectedExecutionException runtime exception, and the application can catch it or discard it.
Following is an example to observe the life cycle of a executor framework. Here we will only discuss the basis steps and the basic interfaces. There are many more properties and subclasses available to handle different kind of applicant need.
The following class implements Runnable and its instances will be used as a task in the next section of code.
public class jobPrint implements Runnable {
private final String name;
private final int delay;
public jobPrint(String name, int delay) {
this.name = name;
this.delay = delay;
}
public void run() {
System.out.println("Starting: " + name);
try {
Thread.sleep(delay);
} catch (InterruptedException ignored) {
}
System.out.println("Done with: " + name);
}
}
The following class is implementing the executor tasks.
import java.util.concurrent.*;
import java.util.Random;
public class UseExecutorService {
public static void main(String args[]) {
Random random = new Random();
ExecutorService executor = Executors.newFixedThreadPool(3);
// Sum up wait times to know when to shutdown
int waitTime = 500;
for (int i=0; i<10; i++) {
String name = “NamePrinter ” + i;
int time = random.nextInt(1000);
waitTime += time;
Runnable runner = new jobPrint(name, time);
System.out.println(“Adding: ” + name + ” / ” + time);
executor.execute(runner);
}
try {
Thread.sleep(waitTime);
executor.shutdown();
executor.awaitTermination
(waitTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignored) {
}
System.exit(0);
}
}
Create an executor
First create an instance of an Executor or ExecutorService. The Executors class has a number of static factory methods to create an ExecutorService. For example, newFixedThreadPool() returns a ThreadPoolExecutor instance with an initialized and unbounded queue and a fixed number of threads. And newCachedThreadPool () returns a ThreadPoolExecutor instance initialized with an unbounded queue and unbounded number of threads. In the 2nd case, existing threads are reused if available.If no free thread is available, a new one is created and added to the pool. Threads that have been idle for longer than a timeout period will be removed automatically from the pool.
This is a fixed pool of 15 threads.
private static final Executor executor = Executors.newFixedThreadPool(15);
This is a cached thread pool
private static ExecutorService exec = Executors.newCachedThreadPool();
Following is a customized thread pool executor. The parameter values depend upon the application need. Here the core pool is having 5 threads which can run concurrently and the maximum number is 10. The queue is capable of keeping 200 tasks. Here one point should be remembered that the pool size should be kept on a higher side to accommodate all tasks. The idle time limit is kept as 5 ms.
private static final Executor executor = new ThreadPoolExecutor(5, 10, 50000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(200));
Create one or more tasks and put in the queue
Create one or more tasks to be performed as instances of either Runnable or Callable.
Submit the task to the Executor
After creating the ExecutorService, you need to submit a task to it by using either submit () or execute () method. Now a free thread from the pool will automatically take the tasks from the queue and execute it. Now the process will continue till all the tasks are finished from the queue.
Execute the task
Now the Executor is responsible for managing the task’s execution, thread pool and queue. If the pool has less than its configured number of minimum threads, new threads will be created to handle queued tasks until that limit is reached to the configured value. If the number is higher than the configured minimum, then the pool will not start any more threads. Instead, the task is queued until a thread is freed up to process the request. If the queue is full, then a new thread is started to handle it.
Shutdown the Executor
The termination is executed by invoking its shutdown () method. You can choose to terminate it gracefully, or abruptly.
This is a great post on multitasking in java
Thanks
/Jhon