CODEXE

AJAX Long Polling

Client code


      function getCommentUpdate() {
	  $.ajax({
		type:'POST',
	    url: '/realtime/comment',
	    cache:false,
	    success: function(data) {
	        if(data==='0'){
	        	//hide notification icon
	        	$(".realtime-comment").hide();
	        	$(".update-remind").hide();
	        }
	        else{
	        	//show notification icon
	        	$(".realtime-comment").find(".commentnum").html(data);
	        	$(".realtime-comment").show();
	        	$(".update-remind").css('display','inline-block');
	        }
	    },
          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 {
                console.log(status);
                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