Java Reference
In-Depth Information
ABOUT FUTURE<?>
While GUI programmers might be used to it by now,
Future<?>
is perhaps not something com-
monly encountered by web programmers.
Future
s were first introduced in Java 5 as part of the con-
currency library. A
Future
represents an abstract task that bears some result, and provides methods
for managing the life cycle of such a task. These methods allow you to check if a task has been can-
celled, to check if it is complete, and to collect the result of the task. You can also cancel the task if
desired, and specify an amount of time you want to wait for the task to complete before throwing a
TimeoutException
. The tasks themselves are usually described by an implementation of the
Run-
nable
or
Callable
interfaces, and
Future
generally wraps them.
The method used to collect the result of the task the
Future
represents is
get
, which waits if neces-
sary.
Behind the scenes, the
Future
will put the result into the handler, which you can use to per-
form additional work once the result is ready.
NOTE
Given the way that
Future<?>
works, you do not want to retrieve the result directly from the
Fu-
ture
object itself. The “?” represents a wildcard with no upper bound and has no standard type,
which means the effective type is
Object
. So while it is possible to do this:
DoLongJobResponse r = (DoLongJobResponse)task.get();
clients are discouraged from casting the result in this manner, as it could lead to non-portable behavi-
or. Instead, use the handler implementation to retrieve the result if necessary.
Make sure that you invoke
isDone
before attempting to use the result. If it is not yet ready,
the future's
get
returns null.
Writing the callback handler
A callback handlers can be implemented for dispatch clients or SEI clients. It is just a class
that implements the
AsyncHandler
interface, which defines the single method
handleRe-
sponse
.
Within a callback handler, the developer has access to the following:
▪ The JNDI context at
java:comp/env
▪ The resource managers
▪ Enterprise Java Beans