Java Reference
In-Depth Information
A task that executes in a thread and returns a result must implement the
Callable<>
interface that declares
the
call()
method. The result that the
call()
method returns is the result of executing the task. You can
execute a
Callable<>
task in a thread pool like this:
Future<String> future = threadPool.submit(callableTask);
This statement executes the task,
callableTask
, and the
future
object encapsulates the result of execut-
ing the task that, in this instance, is an object of type
String
.
All versions of the
submit()
method throw an exception of type
NullPointerException
if the task ar-
gument is
null
and throw an exception of type
java.util.concurrent.RejectedExecutionException
if the task cannot be executed for some reason.
Future<V> Object Methods
The
Future<>
reference that the
submit()
method returns is returned immediately, before the task com-
pletes execution. The
Future<>
object therefore provides a way to access the executing task and determine
its state. You can use the
Future<>
object to cancel execution of the task to which it relates:
if(future.cancel(true)) {
System.out.println("Task has been cancelled.");
} else {
System.out.println("Task could not be cancelled.");
}
The argument to the
cancel()
method should be specified as
true
if the task should be interrupted. If
you specify the argument as
false
and the task is still executing, it is allowed to continue. The method re-
turns
false
if the task could not be cancelled and
true
otherwise.
You can call the
isCancelled()
method for a
Future<>
object to determine whether or not the task was
canceled before it completed normally. The method returns
true
if the task was canceled and
false
other-
wise. If the task has ended, calling the
isDone()
method returns
true
; it returns
false
if the task is still
running.
You obtain the result of executing a task by calling the
get()
method for the
Future<>
object that relates
to it. There are two versions of
get()
. The first has no parameters and you call it like this:
String result = null;
try {
result = future.get();
} catch(CancellationException e) {
System.out.println("Task was cancelled before a result was obtained.");
} catch(InterruptedException e) {
System.out.println(
"Current thread was interrupted while awaiting a result.");
} catch(ExecutionException e) {
System.out.println("Task threw an exception: ");
Throwable cause = e.getCause();
if(cause == null) {
System.out.println("Cause could not be determined.");
} else {
System.out.println(cause);
}