Reputation: 173
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.
Upvotes: 2
Views: 1941
Reputation: 26264
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();
Upvotes: 0
Reputation: 3623
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.
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.
Upvotes: -1
Reputation: 403441
Executor
using java.util.concurrent.Executors.newCachedThreadPool
(or one of the other factory methods) in your controller/servlet's initialization method.java.lang.Runnable
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).
Upvotes: 3