2

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.

AbSoLution8
  • 1,203
  • 1
  • 18
  • 27

2 Answers2

1

Why not use a BlockingQueue? I don't undestand why this has anything to do with jQuery and long polling. This is a server internals design problem.

gabor
  • 400
  • 3
  • 12
0

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...

Community
  • 1
  • 1
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243