Today is a good day to code

Java ExecutorService and the Executor Class

Posted: December 31st, 1969 | Author: | Filed under: Uncategorized | No Comments »

Java ExecutorService and the Executor Class

Picture of IrvinOne of the cool features built into Java 1.5 ( yes I know 1.6 is out ), is the ExecutorService. What it does is it allows you to create an instance of a thread pool that will easily allow you to re-use threads. It also makes it easy to keep your J2SE application running while you perform different tasks without creating a reference loop with a sleeping thread.

So here's how you can do it. I use the fixed thread pool because I don't want the trouble of having to manage all of the functions to deal with threads that have completed and instantiating new threads. Also, I don't want the overhead. One way you can build it is as a static singleton. You will probably always want to do it that way, I won't do it here though.

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class someClass {
private final ExecutorService myExecutor;

// the constructor
public someClass() {
myExecutor = Executors.newFixedThreadPool(10);

With this snippet, obviously you would need a full class, etc, but at this point you would have an instance of a thread pool that would handle all of the queuing and sleeping of threads when they were not in use.

Once you have this, you can then execute a Runnable class instance with the execute method.

pool.execute(new MyRunnableTask(constructorArg1,constructorArg2));

At this point you have a running task. The thing to remember is that once this task completes, the pool will remain. In fact, the application will never stop. To tell the pool to stop and end after all running tasks complete, use this command:

pool.shutdown();

This will stop the executing of the pool. Doing threading this way makes Java much easier to handle than most any language. Just watch out for implicitly synchronized objects such as the Vector, they'll slow your threading down.