| By Calvin Austin | Article Rating: |
|
| October 26, 2004 12:00 AM EDT | Reads: |
25,509 |
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.
Published October 26, 2004 Reads 25,509
Copyright © 2004 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
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.
![]() |
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. |
||||
- Cloud CEOs, CTOs & SVPs to Speak at 4th International Cloud Computing Expo
- Kindle 2 vs Nook
- Why IBM’s Server Chief Got Busted
- The Difference Between Web Hosting and Cloud Computing
- Cloud Computing Journal Opens "Readers' Choice Awards" Nominations
- Cloud Computing Expo: Exclusive Q&A with Yahoo! SVP Cloud Computing
- Industry Experts Discuss the State of Cloud Computing
- Ajax in RichFaces 3.3, JSF 2 and RichFaces 4
- It's the Java vs. C++ Shootout Revisited!
- The End of IT 1.0 As We Know It Has Begun
- An Introduction to Abbot
- Java Kicks Ruby on Rails in the Butt
- Interviewing Java Developers With Tears in My Eyes
- Cloud CEOs, CTOs & SVPs to Speak at 4th International Cloud Computing Expo
- 1st Annual Government IT Expo: Call for Papers Deadline July 15
- How to Diagnose Java Resource Starvation
- REA Is Where RIA Becomes the Norm
- Kindle 2 vs Nook
- Anatomy of a Java Finalizer
- Why IBM’s Server Chief Got Busted
- A Cup of AJAX? Nay, Just Regular Java Please
- Java Developer's Journal Exclusive: 2006 "JDJ Editors' Choice" Awards
- The i-Technology Right Stuff
- JavaServer Faces (JSF) vs Struts
- Rich Internet Applications with Adobe Flex 2 and Java
- Java vs C++ "Shootout" Revisited
- Bean-Managed Persistence Using a Proxy List
- Reporting Made Easy with JasperReports and Hibernate
- Creating a Pet Store Application with JavaServer Faces, Spring, and Hibernate
- What's New in Eclipse?


































