Java Reference
In-Depth Information
The
Future
interface is defined within the
java.util.concurrent
package that comes with
the JDK. For JAX-RS, it gives us a nice reusable interface for polling HTTP responses in
either a blocking or nonblocking manner. If you've used
java.util.concurrent.Executors
or
@Asynchronous
within an EJB container, using the
Future
interface should be very familiar to you.
package
package
java
.
util
.
concurrent
;
public
public interface
interface
Future
Future
<
V
> {
boolean
boolean
cancel
(
boolean
boolean
mayInterruptIfRunning
);
boolean
boolean
isCancelled
();
boolean
boolean
isDone
();
V
get
()
throws
throws
InterruptedException
,
ExecutionException
;
V
get
(
long
long
timeout
,
TimeUnit unit
)
throws
throws
InterruptedException
,
ExecutionException
,
TimeoutException
;
}
This is best explained in a full example:
Client client
=
ClientBuilder
.
newClient
();
Future
<
Response
>
future1
=
client
.
target
(
"http://example.com/customers/123"
)
.
request
()
.
async
().
get
();
Future
<
Order
>
future2
=
client
.
target
(
"http://foobar.com/orders/456"
)
.
request
()
.
async
().
get
(
Order
.
class
);
// block until complete
Response res1
=
future1
.
get
();
Customer result1
=
res
.
readEntity
(
Customer
.
class
);
// Wait 5 seconds
try
try
{
Order result2
=
future2
.
get
(
5
,
TimeUnit
.
SECONDS
);
}
catch
catch
(
TimeoutException timeout
) {
...
handle exception
...
}
In this example, two separate requests are executed in parallel. With
future1
we want a full
javax.ws.rs.core.Response
. After executing both requests, we poll and block indefinitely
on
future1
by calling
Future.get()
until we get a
Response
back from that service.