Java Magazine, Jan/Feb 2016
ORACLE COM JAVAMAGAZINE JANUARY FEBRUARY 2016 43 web apps processing enabled we can use a diferent thread to process the request and dispatch a response to the user This change frees the original servlet request thread right away so that it is returned to the servlet container to service other requests from other users Servlet 30 makes coding asynchronous processing simple by introducing AsyncContext an execution context for asynchronous operations AsyncContext encapsulates servlet request and response and lets you work with them outside of the original servlet processing thread To use AsyncContext you first need to indicate your intent to the servlet container for example by adding asyncSupported true to your servlet annotation Then to put a request into asynchronous mode you need to create an instance of AsyncContext inside the servlets service call method This can be done with AsyncContext asyncContext request startAsync request response At this point the asynchronous request processing can be delegated to a different thread or put in a queue for processing later Because servlet request and response objects are encapsulated with AsyncContext they are available to any thread and are not tied to the original servlet thread This allows the original servlet thread to finish the service call without waiting for the asynchronous response to be completed and to be available to service requests from other clients A Simple Example of Asynchronous Long Polling Lets look at the simple example of a web chat application that demonstrates the advantages of asynchronous servlet processing In this application the user types a username and a message and then clicks Send see Figure 1 This message will then appear on all the browsers polling the chat URL Figure 1 Chat app that broadcasts incoming messages The code in Listing 1 shows the key communication portions of the chat app Listing 1 @ WebServlet urlPatterns chatApi asyncSupported true loadOnStartup 1 public class AsyncChatServletApi extends HttpServlet private static final int NUM_ WORKER_ THREADS 10 Lock lock new ReentrantLock LinkedList AsyncContext asyncContexts new LinkedList private AsyncListener listener new ChatAsyncListener @ Override public void doGet HttpServletRequest request HttpServletResponse response throws IOException AsyncContext asyncContext
You must have JavaScript enabled to view digital editions.