Search code examples
javatomcattomcat6background-process

tomcat background threads


I have a tomcat 6.20 instance running, and would like to send an email via a background thread to prevent the email sending function from blocking the request.

Is there any way I can execute the thread in the background, while still allowing normal page flow to occur.

The application is written in ICEfaces.

Thanks.


Solution

    1. Create an Executor using java.util.concurrent.Executors.newCachedThreadPool (or one of the other factory methods) in your controller/servlet's initialization method.
    2. When a request comes in, wrap the mail-sending logic in a java.lang.Runnable
    3. Submit the Runnable to the Executor

    This will perform the sending in the background. Remember to create a single Executor at startup, and share across all the requests; don't create a new Executor every time (you could, but it would be a bit slow and wasteful).