Java Reference
In-Depth Information
Here the tasks run and complete under the control of the Executor ,which
reuses threads from the thead pool as needed without incurring the overhead of
always creating new threads. There are several more Executor factories in the
Executors class for other needs beyond the scope of this topic. Refer to the
J2SE 5.0 API docs for complete information [1-3].
10.8.2 The Callable interface
The new java.util.concurrent.Callable interface is much like
Runnable but overcomes two drawbacks with Runnable . The run() method
in Runnable cannot return a result (it must be declared to return void ) and
cannot throw a checked exception. If you try to throw an exception in a run()
method, the javac compiler insists that you use a throws clause in the method
signature. But if you then declare the run() method to throw an exception,
javac tells you that the overridden run() method does not throw any excep-
tions. That is, the superclass run() method, or in this case the method defined
in the Runnable interface, does not throw any exceptions, so any overriding
methods cannot throw exceptions either.
If you need a result from a Runnable task, you have to provide some external
means of getting that result. A common technique is to set an instance variable in
the Runnable object and provide a method to retrieve that value. For example,
public MyRunnable implements Runnable
{
private int fResult = 0;
public void run () {
...
fResult = 1;
}
public int getResult () { return fResult; }
} // class MyRunnable
The Callable interface solves these problems. Instead of a run() method the
Callable interface defines a single call() method that takes no parameters
but is allowed to throw an exception. A simple example is
import java.util.concurrent.*;
public class MyCallable implements Callable
{
public Integer call () throws java.io.IOException {
return 1;
}
} // MyCallable
Search WWH ::




Custom Search