Look into the new Java concurrency facilities (in the java.util.concurrent
package) which have been added in Java 5. It provides functionality that is more high-level than regular Thread
s which will make it easier (and less error-prone) to write concurrent applications. The Lesson: Concurrency of The Java Tutorials would be a good place to start.
So far, I've only used the ExecutorService
, which allows can produce thread pools, to which new tasks can be handed off in units of Runnable
s or Callable
s (which can return values after execution as Future
s), and the actual threading code is handled by the ExecutorService
.
For example, performing some calculation using a thread pool of 2 threads, and getting the result can be as simple as:
ExecutorService es = Executors.newFixedThreadPool(2);
Future f1 = es.submit(new Callable<Integer>() {
public Integer call()
{
// Do some processing...
return someInteger;
}
});
Future f2 = es.submit(new Callable<Integer>() {
public Integer call()
{
// Do some processing...
return someInteger;
}
});
Integer firstInteger = f1.get();
Integer secondInteger = f2.get();
In the above (untested) code, all I have to worry about is making a couple of Callable
s and submit
ing it to the ExecutorService
and later on, using the Future
s to retrieve the result.
The catch is, once the get
method of the Future
is called, if the processing isn't complete, the program will stop until the result of the Future
can be retrieved. So, in this example, even if the result of f2
is available before f1
, the program will wait until the result of f1
is available.
In terms of reading material, on my list of books to purchase soon is Java Concurrency in Practice by Brian Goetz, which comes up often when concurrency in Java is brought up.
The Concurrency Utilities page from the Java 5 documentation has more information as well.