0

I'm still new to multi-threading and I'm not sure how to implement this. I have this Spring app that I would like to be able to send from the controller OK status when it is called say from Postman, while the method called in it still finished in the background. Can I ask for example code how to do this? Here is the method I would like to make asynchronous:

public void methodForAsynchronousTask(){
    restTemplate.exchange(url, method, requestEntity, String.class);
}

And this is my controller:

@PostMapping("/")
public ResponseEntity<?> startOutage() {
    someClass.methodForAsynchronousTask();
    return new ResponseEntity<>(HttpStatus.OK);
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Stella
  • 23
  • 4
  • Does this answer your question? [How to asynchronously call a method in Java](https://stackoverflow.com/questions/1842734/how-to-asynchronously-call-a-method-in-java) – luk2302 Apr 06 '21 at 07:29

1 Answers1

0

I would use an ExecutorService inside your someClass implementation, limiting the number of threads created:

@Component
public class SomeClass {
  
  private ExecutorService executorService;
  private RestTemplate restTemplate;
  
  public SomeClass() {
    this.executorService = Executors.newFixedThreadPool(10);
    this.restTemplate = new RestTemplateBuilder().build();
  }  

  public someMethodForAsynchronousTask() {
    executorService.submit( () -> {
      restTemplate.exchange(url, method, requestEntity, String.class);
      .. // and whatever else
    });
  }
}
  • Thank you for this suggestion @christianfoleide, it worked and is a really elegant solution – Stella Apr 12 '21 at 14:12