Question

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.

Was it helpful?

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).

OTHER TIPS

Put your email sending in place of Thread.sleep(). Put your output in place of sendRedirect().

public void doUrlRequest(HttpServletRequest request, HttpServletResponse response) {
    try {
        response.sendRedirect("/home");
    } catch (IOException e) {
        CustomLogger.info(TAG, "doUrlRequest", "doUrlRequest(): "+e.getMessage());
    }
    (new Thread() {
        public void run() {
            try {
                Thread.sleep(9000);
                System.out.println("Awoken!");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }).start();

I have found a way out. These tags

@PostConstruct()

and

@PreDestroy()

Create 2 methods in your servlet that return void and accept no parameters. place the 1st tag immediately above the first method and the 2nd tag above second tag.

Essense of the Tags

The @PostConstruct method is called by the container before the implementing class begins responding to web service clients.

The @PreDestroy method is called by the container before the endpoint is removed from operation.

inside the PostConstruction() method create your thread using the runnable interface and have it run in an infinite loop unless the value of a certain boolean variable is false.

use the PreDestroy() method to set the boolean variable to false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top