L. Heider
L. Heider

Reputation: 1819

Asynchronous programming in Java - Background processes

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?

Upvotes: 0

Views: 65

Answers (1)

L. Heider
L. Heider

Reputation: 1819

        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!

Upvotes: 1

Related Questions