Java Reference
In-Depth Information
3.5.5. Using the Future interface
Unless your method is a fire and forget, you'll probably be interested in the results of the
method call. To work with results from an asynchronous method, you must return an ob-
ject implementing the
java.util.concurrent.Future
interface. The
Future
in-
terface has the following methods:
•
boolean cancel(boolean mayInterruptIfRunning)—
This cancels
the operation.
•
V get()—
This returns the value and blocks until the result is available.
•
V get(long timeout, TimeUnit unit)—
This returns the result or null
if the result isn't available in the specified time limit.
•
boolean isCancelled()—
This returns true if this task was cancelled.
•
boolean isDone()—
This returns true if the task has completed.
• With the
Future
interface you can do the following tasks:
◦ Cancel the operation.
◦ Retrieve the value of the computation, optionally with a time-out if you
don't want to wait.
◦ Check to see if the operation has either been cancelled or has completed.
The
javax.ejb.AsyncResult
class was added in Java EE 6 as a convenience class
for wrapping the result to be returned so that you don't have to provide your own imple-
mentation of
Future
. An asynchronous method creates an instance of
AsyncResult
and passes in the “payload” that will be returned to the caller, as you can see in
listing
task has been cancelled via the
Future
interface by calling the static
SessionCon-
text.wasCancelCalled()
method. If the operation has been cancelled, the method
should bail at this point, because the result of the operation will be ignored. The
Asyn-
cResult
class makes passing back asynchronous data easy.
3.5.6. Using asynchronous session beans effectively
The
@Asynchronous
annotation is very powerful and potentially dangerous. Using this
annotation too liberally will have a detrimental impact on performance. Threads have a
large resource footprint and thus there's an upper limit to the number of threads. Either the
limit may be operating system-dependent or the application container may limit the num-