Understanding Executors

Executors (and ThreadPools used by them) help meet two of the same needs that Threads do:

  • creating and scheduling some Java code for execution
  • optimizing the execution of that code for the hardware resources you have available (using all CPUs, for example)

With Executors, developer handles need 1. ThreadPools help in handling need 2.

Executor is an alternative to starting new threads, it replaces manual thread creation. Generally, using Executors help with decoupling tasks that are to be performed (Runnable instances) from tread creation and starting. The basic usage is something like this:

Runnable r = new MyRunnableTask();
Executor ex = // details to follow
ex.execute(r);

Unlike a more traditional new Thread(r).start(), an Executor can be designed to use any number of of threading approaches, including

  • not starting any threads at all (task is run in the calling thread)
  • starting a new task for each thread
  • queuing tasks and processing them with only enough threads to keep the CPU utilized

Following example does not start any new threads; instead, it executes the Runnable using the thread that invoked the Executor.

import java.util.concurrent.Executor;
public class SameThreadExecutor implements Executor {
@Override
public void execute(Runnable command) {
command.run(); // caller waits
}
}

Next example would use a new thread for each task:

import java.util.concurrent.Executor;
public class NewThreadExecutor implements Executor {
@Override
public void execute(Runnable command) {
Thread t = new Thread(command);
t.start();
}
}

And this example shows how an Executor implementation can be put to use:

Runnable r = new MyRunnableTask();
Executor ex = new NewThreadExecutor(); // choose Executor
ex.executor(r);

As it was mentioned above, with using Executor interface the submission of tasks is decoupled from execution of tasks. So, one can easily modify how threads are used to execute tasks in applications. About threadfactories

Leave a Reply

Your email address will not be published. Required fields are marked *