|
Comments
Did you read today's front page stories & breaking news?
SYS-CON.TV
|
Features Mastering Multithreading
Mastering Multithreading
By: Calvin Austin
Oct. 26, 2004 12:00 AM
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. Reader Feedback: Page 1 of 1
Your Feedback
Latest Cloud Developer Stories
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
|
SYS-CON Featured Whitepapers
Most Read This Week
Breaking Cloud Computing News
|
||||||||||||||||||||||||||||||||||||||||||||||||||||