简体   繁体   中英

Using Java Executor Service In Online Application

I have one functionality in online application. I need to mail receipt to customer after generate receipt. My problem is mail function takes more time nearly 20 to 30 seconds, customer could not wait for long time during online transaction.

So i have used java ExecutorService to run independently mail service [sendMail] and return response PAGE to customer either mail sent or not.

Is it right to use ExecutorService in online application [Http request & Response]. Below is my code. Kindly advice.

@RequestMapping(value="/generateReceipt",method=RequestMethod.GET)
public @ResponseBody ReceiptBean generateReceipt(HttpServletRequest httpRequest,HttpServletResponse httpResponse) {

// Other codes here 
...
...

I need run below line independently, since it takes more time. so commeneted and wrote executor service
//mailService.sendMail(httpRequest,  httpResponse, receiptBean);

java.util.concurrent.ExecutorService executorService = java.util.concurrent.Executors.newFixedThreadPool(10);
executorService.execute(new Runnable() {
    ReceiptBean receiptBean1;
    public void run() {
        mailService.sendMail(httpRequest,  httpResponse, receiptBean);
    }
    public Runnable init(ReceiptBean receiptBean) {
        this.receiptBean = receiptBean1;
        return(this);
    }
}.init(receiptBean));
executorService.shutdown();

return receiptBean;
} 

You can do that, although I wouldn't expect this code in a controller class but in a separate on (Separation of Concerns and all).

However, since you seem to be using Spring, you might as well use their scheduling framework .

It is fine to use Executor Service to make an asynchronous mail sending request, but you should try to follow SOLID principles in your design. Let the service layer take care of running the executor task.

https://en.wikipedia.org/wiki/SOLID

I agree with both @daniu and @Ankur regarding the separation of concerns u should follow. So just create a dedicated service like "EmailService" and inject it where needed. Moreover you are leveraging the Spring framework and u can take advantage of its Async feature . If u prefer to write your own async code then I'll suggest to use maybe a CompletableFuture instead of the ExecutorService to better handling failure (maybe u want store messages not sent into a queue for achieving retry feature or some other behaviour).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM