views:

25

answers:

2

I'm looking for an example, how to implement a longpoling mechanism in java. I would love to use a stateless EJB.

I know that something like that would work:

@WebService(serviceName="mywebservice")
@Stateless
public class MyWebService {
    @WebMethod
    public String longPoll() {
         short ct = 0;
         while(someCondition == false && ct < 60) {
             sleep(1000);  // 1 sec
             ct++;
         }
         if (someCondition)
             return "got value";
         else
             return "";
    }
}

Unfortunately i know that this does'nt scale. Can i return in the webmethod without finishing the response and finish it somewhere else?

A: 

The thing you're trying to implement is called server push. Each webserver/appserver has a pool of threads, say 10 threads for processing web requests, if all those threads will go into 'sleep' no other web request will be serviced until one of those 'sleeps' exists. Some solution is to increase number of those threads but then you'll eat more memory and more operating system resources (each thread costs). So yes, your implementation of 'server push' isn't scalable.

Solutions:

  • your web application can send a http request every (say) 5 secs, to check if your 'someCondition' changed, and then get the data
  • AFAIK, Tomcat (so JBoss too) already has some 'connector' for supporting such requests, so Thread.sleep() or semaphores won't be needed
  • use latest web server implementing Servlet API 3, it also has support for such long-running HTTP requests
  • read more: http://stackoverflow.com/questions/824604/online-tutorials-for-implementing-comets-server-push
iirekm
i was aware that my example doesn't scale. it seems like the connector you mean is the APR Connector. Unfortunately i can't find much information on how to use the connector.
Laures
I think that those links should help you: http://tomcat.apache.org/tomcat-6.0-doc/aio.html , http://www.javalobby.org/java/forums/t92965.html . Also keep in mind the Servlet 3 API (which is or will be the standard soon). Tell us about your results.
iirekm
A: 

JAX-WS provides support for invoking Web services using an asynchronous client invocation and supports both a callback and polling model. Have a look at:

Pascal Thivent