• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sending out emails, not hanging application  RSS feed

 
Henrique Boreg
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am developing a feature where I will eventually have to send out lots of emails to different addresses. Since this is done through a mouse button click event, I want to have a different process separate from the web application which will be in charge of actually sending out the emails.

I am having trouble figuring out the best way to design this. I've thought about starting a new java Thread to send out emails but I'm not sure I want to do multi-threaded stuff inside a button's click event inside a web page. I've also thought about developing a separate application which would work as a kind of a standalone server whose only function would be to send out emails.

Any better ideas?
Thanks.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Running a separate Thread to send emails is the best approach.

The request/response Thread should certainly NOT try to execute time consuming tasks with uncertain outcome.

A separate application would work - you just need to figure out how to hand it the email data.

I have just created a Runnable class started by the servlet init() with a low priority Thread that has a queue of message objects which it tries to send and just sleeps when it has nothing to do.

Bill
 
Henrique Boreg
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.

I've implement the solution by running the "email sender" on a separate thread with MIN_PRIORITY like so:


When I run this code it works fine, but even with min_priority set I am getting a 50% CPU usage.

Is there a way to improve this loop inside the "run" method so it can just sleep until a new email address has been added to the queue?
Thanks.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You forgot to add a sleep call, there is no need to cycle constantly.

See the Javadocs for java.lang.Thread

Thread.currentThread().sleep( 1000 ); // sleep one second


You also need to handle the cases in which sendEmail fails - for example if the mail server is temporarily off-line.

If you make the while() use a public boolean variable, it will be possible to shut the server down in an orderly fashion. Also make the Thread a Daemon - otherwise the running Thread will prevent shutdown of the application.

Bill
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!