Welcome!

Java Authors: Michael Sheehan, Maureen O'Gara, Jonny Defh, Suresh Krishna Madhuvarsu, RealWire News Distribution

Related Topics: Java

Java: Article

Mastering Multithreading

Mastering Multithreading

Some of you may remember a time when the world of multithreaded programming was limited to a small set of C or C++ applications. Often the threads were used sparingly and restricted to a specific task or computation or even operating system.

When the Java platform arrived it brought with it the ability for anyone to write a fully multithreading program, including those with very little experience in using threads. Even the vendors who had the foresight to implement a threading library in the OS found they needed to fix those libraries in order to let these new multithreaded Java programs run.

The original Java threading model had very basic controls. Synchronized methods and blocks were there to guard code and a wait and notify pattern provided limited conditional support. Things were even more confusing when you had a thread start method but the suspend, resume, and stop counterparts were all deprecated! It wasn't too surprising that talks, books, and articles about using Java threads soon became very popular.

One book in particular stood out, partly due to the title but primarily because of the ideas it contained. That book was Concurrent Programming in Java: Design Principles and Patterns by Doug Lea (Addison-Wesley). This book was different because it looked at designing true concurrent, multithreaded programs first, and then applying that to the Java platform. In the process it uncovered areas where the Java APIs were limited. Instead of forcing developers to work around this restriction, Doug created the Java concurrency API library - a library that provided higher-level thread controls, a complement of locks, and finer-grained synchronization tools.

Fast forward to J2SE 5.0, which should be final by the time you read this. I'm pleased to report that the Java concurrency library is now part of the Java platform. Does that mean you should go back and rework every single piece of threaded code you wrote over the last eight years? Not necessarily. However, if you are starting from scratch or refactoring some historically tricky threading code, I would recommend spending a little time checking out what this library has to offer.

Along with synchronization controls like semaphores and explicit calls to create, set, and release locks, there is a significant upgrade to the thread controls. This new functionality is provided by the ThreadExecutor class. You're probably very aware that when you create a runnable task, there is no mechanism to return a result, throw an exception to the parent, or even cancel that task. Where before you may have used a Runnable task, you can now create a Callable one instead. They're very similar; the following is a small example to show how easy this is.

Here is my runnable task, called Worker. In the Callable version all I have to do is describe my return type, in this example a string, and use the new declaration of Callable that has one method named call instead of run. Notice that with Generics we can explicitly declare the return type so it can be checked at compile time.


class Worker implements Callable<String> {
    public String call() {
        System.out.println("New Worker");
        return "return result";
    }
}

To use my task I just need to pick an ExecutorService. In this example I chose the cached thread pool, which will create as many threads as I need but will reuse previously constructed threads if available. The logic behind this is that thread creation can be an expensive operation on some systems.

I create my Callable task, called task, and then create a handle to that task, a Future, that I have named result. The Future task serves two purposes. The first is that I can cancel the task by calling the method result.cancel(true). The true argument means that it's okay to try to cancel an already running task. The second benefit is that it's used to hold the return result. To gain access to the return result, I simply had to call the method result.get().


ExecutorService es = Executors.newCachedThreadPool();
Callable<String> task = new Worker();
Future<String> result;
result=es.submit (task);
try {
    System.out.println(result.get());
}catch(Exception e){}

This small example enabled me to use a cached thread pool to hand off tasks, check their status, and cancel them if required. As I mentioned earlier, I used an ExecutorService that declares some convenient default implementations. The concurrency library has a full set of interfaces and many other implementations that you can use. I encourage you to check the library out along with the other J2SE 5.0 features.

More Stories By Calvin Austin

A section editor of JDJ since June 2004, Calvin Austin is an engineer at SpikeSource.com. He previously led the J2SE 5.0 release at Sun Microsystems and also led Sun's Java on Linux port.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Saptarshi Chandra 10/29/04 01:07:46 AM EDT

It is good to hear that finally some control over Java threads would be available. Heavy duty multithreaded applications were earlier difficult to conceive in java because mere synchronization was not enough to write a multithreaded application. Availability of Mutexes and Semaphores would be really helpful.