0

In my spring boot project , i have below GET web service

@GetMapping("/testThread")
@Transactional
public Map<String, Object> testThread(HttpServletRequest request) throws InterruptedException {

for (int i=0;i<10;i++){
    Thread.sleep(3000);
    System.out.println(i);
}
    return null;
}

This web service i am calling from postman and inside the web service thread is starting , thread is running 10 times .

My requirement is after calling web service from postman after 10 seconds i am able to cancel that request by "Cancel Request" button, then backend thread also should be stop.

As of now its running 10 times .

Do we have any option to stop the execution of this loop in between ?

Harish Bagora
  • 686
  • 1
  • 9
  • 26
  • Actually i am not talking about the thread we can say its background process , if i hit rest service from postman then this loop will start and after 5 -10 seconds i cancel the request . Then do we have any option to stop the execution of this loop ? – Harish Bagora Apr 03 '19 at 14:29
  • Use ExecutorService and submit your job to id, generate ID and associate it with Future returned by ExecutorService. Use another REST call to request cancellation based on generated ID. – rkosegi Apr 03 '19 at 15:38
  • @rkosegi Could you please brief little bit more , how can i generate id and how can i associate with executor service and how can i cancel it by using another rest ? It would be good if you can provide some code sample for this . – Harish Bagora Apr 04 '19 at 06:41

1 Answers1

-1

A trivial solution would be to get from testThread method the of id of the thread, maybe with method:

Thread.currentThread().getId()

After this you can create another Rest Controller that accepts an id thread in input and kill it. But it is not a safe solution