Java Magazine, Jan/Feb 2016
ORACLE COM JAVAMAGAZINE JANUARY FEBRUARY 2016 44 web apps request startAsync request response asyncContext setTimeout 1 asyncContext addListener listener try lock lock asyncContexts addFirst asyncContext finally lock unlock @ Override public void doPost HttpServletRequest request HttpServletResponse response throws IOException final String message getMessage request Collection AsyncContext localCopy try lock lock localCopy asyncContexts asyncContexts new LinkedList finally lock unlock for AsyncContext asyncContext localCopy Runnable runnable new RunnableWriter asyncContext message executor execute runnable localCopy clear private String getMessage class RunnableWriter implements Runnable private final AsyncContext asyncContext private final String message public RunnableWriter @ Override public void run try PrintWriter writer asyncContext getResponse getWriter writer println message writer flush asyncContext complete catch Exception e This code example implements an asynchronous servlet that is tied to the chatApi path A collection is created in which the multiple asynchronous contexts are stored It contains servlet contexts that are waiting to receive a chat message once it is available So instead of tying up servlet processing threads to wait until someone sends a chat message the AsyncContext is created and stored right away to be processed at a later time when a new chat message becomes available Two REST APIs are used doGet and doPost which are shown here as the first two methods in the AsyncChat ServletApi class doGet subscribes a user to receive a new chat message while doPost pushes a new chat message to all waiting clients Specifically when the user hits a get URL an asynchronous context is created by calling AsyncContext asyncContext request startAsync request response Following that the asynchronous context is saved in a list of contexts This is a list representing clients that are waiting to get the next chat message At this point the server thread
You must have JavaScript enabled to view digital editions.