views:

30

answers:

1

Hi I have design/architecture question. I would like to send emails from one of my jsp pages. I have one particular issue that has been a little bit of a problem. there is an instance where one of the pages will need to send around 50 emails at near the same time. I would like the messages sent to a queue where a background thread will actually do the email sending. What is the appropriate way to solve this problem? If you know of a tutorial, example code or tomcat configuration is needed please let me know.

Thanks,

A: 

Your solution is rather sound: append the messages to a internal queue and then let some background task handle them.

Here are a few pointers that may be useful:

  • Unless you want to go distributed (in which case you should look at JMS), use a BlockingQueue implementation for your queue. In your background thread, just do an infinite loop while take()-ing messages from the queue. Those classes take care of potential concurrency issues for you.
  • Use a ServletContextListener to set up your background thread when your Web application starts and when it is stopped.

One possible problem with using a raw BlockingQueue is that when your Web application is stopped, all the messages in the queue are lost. If that's a serious problem, then it would probably be easiest just to use a database for the queue and to use notify() to wake up your background thread, which then processes all requests from the database.

andri
Cool thank you for the answer. This worked like a charm.
Eric V
One more question how do you access the thread that the contextListener has started?
Eric V
Keep the reference to either the queue or the thread (preferrably the thread) in a static variable or in a property of the `ServletContext`. Or, preferrably, if you use some IoC container like Spring to build your application, let it take care of the injection for you.
andri