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
final WebTarget target = client . target ( "http://quote.com/quote/RHT" );
target . request (). async (). get ( new
new InvocationCallback < String > {
public
public void
void completed ( String quote ) {
System . out . println ( "RHT: " + quote );
target . request (). async (). get ( this
this );
}
public
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
public class
class RHTQuoteResource
RHTQuoteResource {
protected
protected List < AsyncResponse > responses ;
@GET
@Produces ( "text/plain" )
public
public void
void getQuote ( @Suspended AsyncResponse response ) {
synchronized
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
final List < AsyncResponse > responses = ...;
Search WWH ::




Custom Search