JavaOne update: the new threading package in J2SE 5

My favorite technical session of the day was the new concurrency utility package scheduled for release this fall in J2SE 5. (the newly rebranded J2SE 1.5.) If you're writing multi-threading applications today and you're not using Doug Lea's package, get it. The new java.util.concurrent package is based on it.

The session was conducted by Brian Goetz and David Holmes, both on the JSR 166 experts group.

The new concurrent package offers higher performance for multi-threaded applications in a package that's easier to use than using synchronize blocks and calling wait() and notifyAll() in a while loop. As David Holmes said in the session, if you find yourself synchronizing a block of code, look at the new concurrent package for a better solution.

The new java.util.concurrent package offers:

  • Built in thread pools
  • A class to let you schedule a runnable
    The runnable may execute at a certain time from now, on a specific date, or run on a regular interval.
  • New concurrency-friendly Collections classes
    As Brian Goetz said, you can get thread-safe Collections objects in Java 1.2+, but those collections aren't concurrency friendly. I.e. they don't run efficiently in a multi-threaded environment.
  • Atomic variables
    These are thread-safe variables you can get and set in a multi-threaded environment without worrying about synchronizing access.

An example from the session: Instead of writing:

Runnable r = ...
new Thread(r).start();

and creating a new, and potentially unlimited number, of threads each time, you'd write:

Executor pool = Executors.newFixedThreadPool(10);
...
Runnable r = ...
pool.execute(r);

to ensure your runnables are executed in a maximum of 10 threads, that are reused and not left around as garbage upon each use.

The new threading package should make threading easier to use for those times when you must use threads, don't want to write a lot of synchronized blocks with notification loops, and want to use a standard Java package.