Search code examples
javamultithreadingperformancereturnexecution

Code to execute after return statement


Just curious to improve the response time of my program with following idea, please help in executing it :

@Controller   
public class SendData{  
   @RequestMapping(value = "/getEmailId", method = RequestMethod.GET)  
   public String getUserMail(String userId) {  
      //getting Email Id From Database
      String emailId = getEmailIdFromDatabase(userId); 

      //send mail
      sendNotificationMail(emailId);

      // send data to requestor
      return emailId;  
     }  
}

Possible idea: To send Mail after returning EmailId to requestor

@Controller   
public class SendData{  
   @RequestMapping(value = "/getEmailId", method = RequestMethod.GET)  
   public String getUserMail(String userId) {  
      //getting Email Id From Database
      String emailId = getEmailIdFromDatabase(userId); 

      // send data to requestor
      return emailId;  

      //send mail
      sendNotificationMail(emailId);
     }  
}

As I am doing it in bit large scale (eg. I am getting list of emailIds) so I want requestor to first get the emailIds and remove the waiting time to send them notification mail.

  • Please tell the solution if it is achievable by threading.
  • If something like this is possible in any language other than Java?
  • I have tried using finally block, but observed finally block executes before return statement.

Solution

  • One possible and naive solution is just to start a new thread for mail sending:

    new Thread() {
        @Override
        public void run() {
            sendNotificationMail(emailId);
        }
    }.start();
    

    A more robust version is to split between "I want send a mail" and "I send a mail". For example, instead of sending a mail just insert that mail in a table. With @Scheduled get inserted mail from the database, send it and delete it after that. So you can improve your response time. That it's. Sure, it's just an idea and you can use message bus or like, but you get the point.