0

I have a servlet that takes a couple of minutes to process and return its response. It is running in a somewhat restricted environment (Amazon Elastic Beanstalk). In this environment, there is a 60 second limit on request times and that is not configurable.

What are my options here? I thought of having the servlet start a thread and have the browser poll with AJAX, but I have seen so many people recommend against servlets starting threads for various reasons.

Another solution would be to have a thread start and end in the application's context listener, but I have many different servlets in the app that perform various functions, all of which have the same issue. A single thread running in the background would not really help.

Any suggestions?

Edit: With a little bit of more research in SO, I found that an Executor is what I need.

See BalusC's answer here

See skaffman's answer here

Community
  • 1
  • 1
stepanian
  • 11,047
  • 8
  • 38
  • 62

2 Answers2

1

Yes, it is not the best practice to start threads programmaticaly into servelet container. But this restriction is not so strict. IMHO you can do it if you really need. But if you are starting such solution implement it step-by-step.

First just try if this works. Open new thread to process your long request. While it is being processed send some kind of "keep-alive" from the "main" thread of your servlet. When processing is done send response to client.

Probably better and more scalable solution is to use messaging (e.g. JMS) for asynchronous processing of long requests. When request is received servlet should just create JMS message , enqueue it and immediately return. The other side (that implements MessageListener) should process message and put the result into outgoing queue. Client should request the result from this queue. The is the clear solution, it will work in clustered and multi-machine environment but it requires more efforts.

So, you choice should depend on your requirements, resources and time.

AlexR
  • 109,181
  • 14
  • 116
  • 194
  • +1 for the thorough response and JMS. But, the answer I was looking for was something like the Executor (see the edits to my question). Thanks. – stepanian Feb 01 '12 at 09:39
  • @stepanian, executor is not magic. It uses thread pool that means that you indirectly create threads that are not managed by your servlet container. – AlexR Feb 01 '12 at 10:43
1

The best way to address this is using the Executor (see the update in my question). I used this in my project and it has worked seamlessly.

stepanian
  • 11,047
  • 8
  • 38
  • 62