Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Java rest api call return immediately not wait?

@RequestMapping(value = "/endpoint", method = RequestMethod.POST)
    public ResponseEntity<?> endpoint(@RequestBody final ObjectNode data, final HttpServletRequest request) {
        somefunction();
        return new ResponseEntity<>(HttpStatus.OK);
    }


public somefunction() {
 .....
 }

In Java spring controller, I have an endpoint. When this endpoint is called, I want it return directly, not wait somefunction() to finish. Any could teach me how to deal with this?

like image 885
c2340878 Avatar asked Dec 01 '16 09:12

c2340878


1 Answers

If you are using Java 8, you can use the new Executor classes:

@RequestMapping(value = "/endpoint", method = RequestMethod.POST)
public ResponseEntity<?> endpoint(@RequestBody final ObjectNode data, final HttpServletRequest request) {
    Executors.newScheduledThreadPool(1).schedule(
        () -> somefunction(),
        10, TimeUnit.SECONDS
    );
    return new ResponseEntity<>(HttpStatus.ACCEPTED);
}

This will:

  1. Schedule somefunction() to run after a 10 second delay.
  2. Return HTTP 202 Accepted (which is what you should return when your POST endpoint does not actually create anything on the spot).
  3. Run somefunction() after 10 seconds have passed.
like image 108
walen Avatar answered Sep 22 '22 08:09

walen