Search code examples
javajquerystruts2long-polling

struts2 long polling with jquery


I have previous experience doing a long polling with PHP and jQuery that check for new chat messages.

The Idea was to have a while loop that checks if there are new messages, if yes, then returns the new message, if no then sleep for 5 seconds and check again.

I would like to do the same using java struts2 framework. I created an action class that has a while loop, does the same, and use Thread.sleep() for the wait.

However I experience some very high CPU usage. Am I doing it right? I apologize that I do not ave any sample code right now because I re-did it using a simple approach that uses client-side polling.

Help appreciated.


Solution

  • If (despite the title saying jQuery), you want to do this in Java ("I would like to do the same using java struts2 framework."), then a while loop is not a good solution;

    Instead, you should use a java.util.Timer ( / TimerTask).

    Please note that in Struts2 one Action is instantiated for every request, so if you create a Timer in the Action, and you have 100 concurrent users, you have 100 timers running. It would be better to use it from an EJB.

    Take a look at this SO answers too:

    1) Timer & TimerTask versus Thread + sleep in Java

    2) How to set a timer in java

    and at the Javadoc: The Java EE 5 Tutorial - Using the Timer Service

    My 2 cents...