Search code examples
javaservletsjava-threads

How to send mail within a servlet using threads or executor service?


I want to send mail based on if a condition

ServletMail.java

//somecodes

//this code should code should be executed in background(by threads or something)

if(cond1){

sendmail(firstcond)

}

else{

sendmail(secondcond)

}

//requestdispatcher

Solution

  • You can use ExecutorService executorService = Executors.newFixedThreadPool(threadNumber); . There threadNumber is concurrent use threads.

    1. If you use IOC then you can declaration bean
    2. Second way simple executorService declaration how static variable;

    You can use it like this

       if(cond1){
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    sendmail(firstcond);
                }
            });
        } else{
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    sendmail(secondcond);
                }
            });
        }
    

    Do not forget put this executorService.shutdown(); to web server shutdown listener.