Java Reference
In-Depth Information
}
The
future
reference here relates to a
Callable<String>
task that returns a
String
object. The
get()
method will block if the task is still running and returns the result when the task has completed. The meth-
od throws
java.util.concurrent.CancellationException
if the task was canceled so the result cannot
be returned. This exception has
RuntimeException
as a base class and need not be caught. The method
can also throw an exception of type
ExecutionException
if the task threw an exception, and, in this case,
calling
getCause()
for the exception object returns a
Throwable
reference identifying the cause of the ex-
ception or
null
if the cause could not be determined. The method throws an exception of type
Interrup-
tedException
if the current thread was interrupted while waiting for the task to complete.
The second version of
get()
enables you to avoid the possibility of the method blocking indefinitely.
It requires two arguments, a value of type
long
specifying the maximum number of time units the
method should wait for the task to complete before returning, and a constant from the
java.util.concurrent.TimeUnit
enumeration that specifies the time unit for the first argument. The enu-
meration defines the following constants:
Obviously, you are most likely to be using
MILLISECONDS
or possibly
SECONDS
as the value for the second
argument to the
get()
method.
Shutting down a Thread Pool
Calling
shutdown()
for an
ExecutorService
object starts the process of shutting down a thread pool by
closing it to new tasks. Existing tasks continue to run. You typically want to wait for tasks in a thread pool
to complete before closing it and the
awaitTermination()
method does that. Here's how you might use it:
threadPool.shutdown();
try {
if(threadPool.awaitTermination(100L, TimeUnit.MILLISECONDS)) {
System.out.println("All tasks completed.");
} else {
System.out.println("Tasks failed to complete.");
}
} catch(InterruptedException e) {
System.out.println("Current thread interrupted awaiting termination.");
}
The
awaitTermination()
waits for tasks in the thread pool to complete for the time you specify by the
two arguments. The method returns
false
if all the tasks did not complete in that timeframe.
You can shut down the tasks in a thread pool by calling its
shutdownNow()
method:
List<Runnable> tasks = threadPool.shutdownNow();
This attempts to shut down all the tasks in the thread pool although the result is not guaranteed. The
method cancels tasks that are running by calling
interrupt()
for each thread so tasks that do not respond
to being interrupted do not shut down. The method returns a reference to a list containing references to those
tasks in the thread pool that were waiting to start execution when shut down occurred.