Java Reference
In-Depth Information
Server-side push
With server-side push, the server is sending events back to the client. A typical example is
stock quotes. The client wants to be notified when a new quote is available. It does a long-
poll GET request until the quote is ready.
Client client = ClientBuilder . newClient ();
final WebTarget target = client . target ( "" );
target . request (). async (). get ( new
new InvocationCallback < String > {
public void
void completed ( String quote ) {
System . out . println ( "RHT: " + quote );
target . request (). async (). get ( this
this );
public void
void failed ( Throwable t ) {}
The preceding continuously polls for a quote using InvocationCallback . On the server
side, we want our JAX-RS resource classes to use suspended requests so that we can have
one thread that writes quotes back to polling clients. With one writer thread, we can scale this
quote service to thousands and thousands of clients, as we're not beholden to a “one thread
per request” model. Here's what the JAX-RS resource class might look like:
@Path ( "quote/RHT" )
public class
class RHTQuoteResource
RHTQuoteResource {
protected List < AsyncResponse > responses ;
@Produces ( "text/plain" )
public void
void getQuote ( @Suspended AsyncResponse response ) {
synchronized ( responses ) {
responses . put ( response );
The example code is overly simplified, but the idea is that there is a List of AsyncResponse
objects that are waiting for the latest stock quote for Red Hat. This List would be shared by
a background thread that would send a response back to all waiting clients when a new quote
for Red Hat became available.
Executor executor = Executors . newSingleThreadExecutor ();
final List < AsyncResponse > responses = ...;
Search WWH ::

Custom Search