AJAX Long Polling

Client code

      function getCommentUpdate() {
	    url: '/realtime/comment',
	    success: function(data) {
	        	//hide notification icon
	        	//show notification icon
          complete: function() {
            // Schedule the next request when the current one's complete
            setTimeout(getCommentUpdate, 60000);
          error: function(jqXHR, status, errorThrown) {
            if (status=='timeout') {
                console.log( 'request timed out.' );
                setTimeout( poll, 10 );
            else {
                setTimeout( poll, 60000 );

Server code

The general desigh is that each servlet handler will make a blocking call to wait for the next push event, and most servlet engines uses a limited thread pool to handle incoming requests, we will face Thread Starvation very soon, with no available threads to handle new incoming requests.

Fortunately Asynchronous Servlets has been introduced since servlet spec 3.0. Instead of waiting for the processing to be finished, the servlet handler simply start another new worker thread, pass along an instance of AsyncContext to the worker thread, and be done. The servlet handler thread is returned to the pool to handle other incoming requests, and with the AsyncContext instance, the new worker thread has everything it needs to complete the request. Check this blog for more details