Java Magazine, Jan/Feb 2016
ORACLE COM JAVAMAGAZINE JANUARY FEBRUARY 2016 45 web apps is done with processing this request and it can be reused for processing other requests When a user issues a doPost request posting a chat message the message is retrieved This message is then written to each of the asynchronous contexts and the processing is completed by calling asyncContext complete Because the servlet can be called by multiple threads the processing thread must be made thread safe In particular three scenarios should be addressed Two post requests are processed simultaneously A get request is received while a post request is being processed Two get requests are processed simultaneously When two posts occur simultaneously or a get and a post occur simultaneously all clients waiting for a message should receive it that is messages are not dropped This can be achieved by synchronizing the copying context into a local collection and reinitializing the member context collection so that it can accumulate new requests Choosing to synchronize the addition of an element to a collection in the doGet method and synchronizing creation of a local copy of a request collection in doPost takes care of both scenarios In the case of two get requests being processed simultaneously both contexts need to be stored for future processing This can be achieved by having a thread safe collection Alternatively it is possible to synchronize the block of code that adds an element as shown in Listing 1 Now lets examine the timeouts If we were to set a noninfinite timeout on the asynchronous context and the timeout is reached clients receive the response Server returned HTTP response code 500 for URL http localhost 8080 chat Api If the timeout is not set explicitly the request inherits the default timeout from the server settings If the timeout is set as 0 or negative as shown in Listing 1 the server never times out the request although a web client can To handle timeouts on the server you can extend AsyncListener and implement custom code in the onTimeout callback event For instance changing the server response to send status code 408 the HTTP code for request timeout along with the message Request timeout no chat messages so far please try again can be achieved by using the code in Listing 2 Listing 2 public class ChatAsyncListener implements AsyncListener @ Override public void onComplete AsyncEvent event @ Override public void onTimeout AsyncEvent event AsyncContext asyncContext event getAsyncContext HttpServletResponse response HttpServletResponse asyncContext getResponse response sendError HttpServletResponse SC_ REQUEST_ TIMEOUT Request timeout no chat messages so far please try again asyncContext complete @ Override public void onError AsyncEvent event @ Override public void onStartAsync AsyncEvent event
You must have JavaScript enabled to view digital editions.