Java Reference
In-Depth Information
Callbacks
The
AsyncResponse
interface also allows you to register callback objects for other types of
events:
package
package
javax
.
ws
.
rs
.
container
;
public
public interface
interface
CompletionCallback
CompletionCallback
{
public
public
void
void
onComplete
(
Throwable throwable
);
}
CompletionCallback.onComplete()
is called after the response has been sent to the client.
The
Throwable
is set to any unmapped exception thrown internally when processing a
re-
sume()
. Otherwise, it is
null
.
package
package
javax
.
ws
.
rs
.
container
;
public
public interface
interface
ConnectionCallback
ConnectionCallback
{
public
public
void
void
onDisconnect
(
AsyncResponse response
);
}
The JAX-RS container does not require implementation of the
ConnectionCallback
. It al-
lows you to be notified if the socket connection is disconnected while processing the re-
sponse.
You enable callbacks by invoking the
AsyncResponse.register()
methods. You can pass
one or more classes that will be instantiated by the JAX-RS container, and you can pass one
or more instances:
response
.
register
(
MyCompletionCallback
.
class
);
response
.
register
(
new
new
MyConnectionCallback
());
Callbacks are generally used to receive notification of error conditions caused after invoking
resume()
. You may have resources to clean up or even transactions to roll back or undo as a
result of an asynchronous failure.
Use Cases for AsyncResponse
The examples used in the previous section were really contrived to make it simple to explain
the behavior of the asynchronous APIs. As I mentioned before, there is a specific set of use
cases for async response processing. Let's go over it.