开发者

Servlets, long operations

I'm refactoring a big piece of code atm where a long taking operat开发者_如何学Cion is executed in a servlet. Now sometimes I don't get a response after the operation has finished. (It has finished because it is printed into the logs)

What I wish to achieve would some "fire and forget" behavior by the servlet. I would pass my params to the action and the servlet would immediately return a status (something like: the operation has started, check your logs for further info)

Is this possible with servlet 2.5 spec? I think I could get such a behavior with JMS maybe any other solutions out there?


Asynchronous Servlets would serve your purpose but it is available only as part of Servlet 3.0 spec. You could read more about Async Servlets here


There are a couple of ways of doing this. Asynchronous servlets are part of the Servlet api 3.0. I've known a lot of people that would fire off a separate thread, usually a daemon thread. The drawback to spawning your own threads is that you lose any "container" advantages you might have, since the thread runs more or less independently within the JVM. What I've used most often is a message driven bean fed by JMS, it runs in the EJB container with all those attendant advantages and disadvantages. YMMV.


Instead of starting (and managing) your own treads you should consider using Java's ExecutorService abstraction (Executor/Future framework). If you're using Spring you can define Executor as just another bean in Spring's context and your servlet could just call it passing your task as instance of Runnable. There should be plenty of samples if you Google it.


If upgrading to Servlet 3.0 (part of Java EE 6, with as far Glassfish v3 as the only implementation; Tomcat 7 is still on its way and expected about next month) is not an option, then an alternative is Comet. Almost all Java servletcontainers has facilities for this. It's unclear which one you're using, so here's a Tomcat 6 targeted document: What is the Apache Tomcat Comet API.

Alternatively, you can fire a separate Thread in a servlet so that the servlet method can directly return. You can eventually store the Thread in the session so that the status can be retained in the subsequent requests. If necessary let it implement HttpSessionBindingListener as well so that you can interrupt it whenever the session expires.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜