Tag Archives: spring

Threading in Spring

In order to know when a user requests a tarot reading, I needed to set up an email client to send a message to me. The joys of SMTP are that sending email is very straightforward, no matter what your programming language. Java is no different. So I created code to send out the message. Problem was, the email was slow to send, slowing the web page response time down too much. I needed to create a second thread to handle it, in order to avoid the slowdown.

I didn’t take the time to read the Spring MVC model documentation first regarding threads. I just moved my email to a class that implemented Runnable and tried to be done with it. Unfortunately, the Spring MVC (or any other servlet for that matter, I’m guessing) requires that all the threads be tied up in pretty bows before proceeding. So using this method to send the email didn’t help my timing issue – it still required the email thread to finish before sending the response page to the user.

A bit more research brought me to Apache’s Active MQ. That was what I needed. It took care of all the heavy lifting for my producer/consumer pieces. I only need to write those classes and call the Active MQ libraries to put it in place.

The one issue I had with the process, after my first foray into it, was that it required a place to write to my file system. It took a bit of digging to figure out how to change the default location to one that my server would allow.

I see that there’s also a way of using my database. That will be another refactoring later.

Here’s the links you need to use this library:

ActiveMQ home page: http://activemq.apache.org

Setup Information for Spring: http://activemq.apache.org/spring-support.html
Tutorial site. A bit out of date (version 3, current version is 5), but it will help you get started: