0

I have got a REST-API in my Java Web Application. This has a method to take orders from a customer's Android app (client) and send (after a bunch of tasks, like price calculating etc.) a response back to the client.

    @POST
    @Path("order")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public OrderResponse takeOrder(OrderRequest request
    ) throws IOException {
        OrderResponse response = new OrderResponse();

        String token = request.getTokenString();
        CustomerSession session = sessionPool.getSession(token);

        if (session != null) {

            OrderHeader order = new OrderHeader();
            order.setFkOrderHeaderCustomerID(session.getFkCustomerID());
            order.setOrderCreationDate(new Date());

Tasks as getting the session for authentication etc. have to be done synchronously, sure. 'Cause the response for the clients depends on it's success or failure.. So far so good.

At the end of this method the client gets an email about the state of his order request.

Email email = EmailGenerator.createOrderEmail(order);
            try {
                emailService.send(email);
            } catch (MessagingException ex) {
                Logger.getLogger(CustomerREST.class.getName()).log(Level.SEVERE, null, ex);
            }


            response.setStatus(OrderStatusEnum.SUCCESS);
        } else {
            response.setStatus(OrderStatusEnum.TOKEN_INVALID);
        }

        return response;
    }

This sometimes takes up to a few seconds for which the client has to wait for the response. That hurts.

Is there any way to send the response and do that email stuff in the background?

L. Heider
  • 1,579
  • 1
  • 14
  • 31

1 Answers1

1
        Thread mailingThread = new Thread() {
            @Override
            public void run() {
                try {
                    Email email = EmailGenerator.createOrderEmail(order);
                    emailService.send(email);
                } catch (MessagingException | IOException ex) {
                    Logger.getLogger(CustomerREST.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };
        mailingThread.start();

Thaks Kyle! This seems to do what I attempted!

L. Heider
  • 1,579
  • 1
  • 14
  • 31
  • No problem! In the future (pun very much intended), you might also take a look at `future`s. They can be handy when you have threads you need to run in parallel and get the results back for use in your program. – Kyle Martin Feb 22 '17 at 19:02