1

I'm working on a dropwizard application. I have a resource, EmployeeResource, which triggers a mail api.

@Path("/employee")
public class EmployeeResource {
    @GET
    @Path("/list")
    public void getEmployeeDetails(){
        //DAO call and other stuff

        mailClient.sendMail();
    }
}

Now, sendMail method will fetch some details from DB, and then make a call to a mail API. I want the method sendMail to not block the "/employee/list" request. Is there a way to make the sendMail method async?

I looked it up and found solutions to make an API async, but I want just my sendMail method to be async. How do I solve this?

Edit: I'm not using Spring framework, just using Dropwizard framework.

user2473992
  • 117
  • 6

1 Answers1

3

To make Async execution of method or any code block you can always create new Thread by implementing the Runnable Interface. For your requirement like below :

@Path("/employee")
public class EmployeeResource {
    @GET
    @Path("list")
    @Async
    public void getEmployeeDetails(){
        //DAO call and other stuff

        new Thread(new Runnable() {
           public void run() {
              mailClient.sendMail();
           }
        }).start();
    }
}

[edit1] If you think concurrency would be high for sending out emails then you can you use ExecutorService which has queue internally (you read more about it here):

private static final ExecutorService TASK_EXECUTOR = Executors.newCachedThreadPool();

Your calling send mail method part code will look like :

TASK_EXECUTOR.submit(new Runnable() {
            @Override
            public void run() {
                mailClient.sendMail();
            }
        });

Abhishek
  • 1,558
  • 16
  • 28