Java Executors
I’m surprised I hadn’t come across these classes before, but Java Executors are great. Added in JDK 1.5, Executors provide built in thread management for all kinds of needs. Below are two simple code fragments.
These two pieces of code are about the same amount of code to spawn a new thread, wait and return. However, the Executor code allows easy replacement of the ExecutorService so that you can use a variety of different thread management and scheduling options. The Executor code uses a simple single threaded executor so that you can queue up jobs, but the JDK also has builtin fixed size thread pools, dynamic thread pools, and you can define your own factory method for thread creation. The Executor also can run older Runnable tasks, but the new Callable interface is more flexible because it can return a value of any type and throw exceptions.
It’s good stuff. Plus it makes me think of Starcraft because the Protoss commanders were called Executors.
import java.util.concurrent.*;
public class ExecutorFun { public static class DoIt implements Callable { public String call() { return "Hello World!"; } }
public static void main(String []args) { try { ExecutorService executor = Executors.newSingleThreadExecutor(); FutureTask task = new FutureTask(new DoIt()); executor.submit(task); System.out.println(task.get()); executor.shutdown(); } catch ( Exception e ) {} }}
Compare that with the following older style code
public class ThreadFun { public static class DoIt implements Runnable { String result; public void run() { result = "Hello World!"; } }
public static void main(String []args) { try { DoIt task = new DoIt(); Thread t = new Thread(task); t.start(); t.join(); System.out.println(task.result); } catch ( Exception e ) {} }}
