deadend
deadend

Reputation: 1376

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;
} 

Upvotes: 0

Views: 513

Answers (3)

Raffaele
Raffaele

Reputation: 511

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

Upvotes: 1

A_C
A_C

Reputation: 925

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

Upvotes: 1

daniu
daniu

Reputation: 15008

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.

Upvotes: 1

Related Questions