Java Reference
In-Depth Information
final
final
Ticker rhtTicker
=
nyse
.
getTicker
(
"RHT"
);
executor
.
execute
(
new
new
Runnable
() {
public
public
void
void
run
() {
while
while
(
true
true
) {
String quote
=
ticker
.
await
();
synchronized
synchronized
(
responses
) {
for
for
(
AsyncResponse response
:
responses
)
response
.
resume
(
quote
);
}
}
}
});
So, here we're starting a background thread that runs continuously using the
Executors
class from the
java.util.concurrent
package that comes with the JDK. This thread
blocks until a quote for Red Hat is available. Then it loops over every awaiting
AsyncRe-
sponse
to send the quote back to each client. Some of the implementation is missing here,
but hopefully you get the idea.
Publish and subscribe
Another great use case for
AsyncResponse
is publish and subscribe applications, an example
being a chat service. Here's what the server code might look like:
@Path
(
"chat"
)
public
public class
class
ChatResource
ChatResource
{
protected
protected
List
<
AsyncResponse
>
responses
=
new
new
ArrayList
<
AsyncResponse
>();
@GET
@Produces
(
"text/plain"
)
public
public synchronized
void
receive
(
@Suspended
AsyncResponse response
) {
responses
.
add
(
response
);
synchronized
void
}
@POST
@Consume
(
"text/plain"
)
public
public synchronized
synchronized
void
void
send
(
String message
) {
for
for
(
AsyncResponse response
:
responses
) {
response
.
resume
(
message
);
}
}
}