Reputation: 482
I tried using the Callable option to set a timeout on a function call, while setting the timeout duration itself in Spring Boot's configuration file (spring.mvc.async.request-timeout).
The code does return after the set timeout, but the problem is that the function itself continues the execution.
I don't have an access to that function's source code, as it's a third party libaray, so I don't have a way to set an interruption-check in that code.
Is there a way to force the termination of the function / the thread once the timeout is over? Am I using the wrong path here and is there another way to achieve this goal?
An example of the current code, which "returns" after the timeout, but doesn't really stop the execution of that code in the background:
@RequestMapping(value = "/api/test", method = RequestMethod.POST, produces = "application/json")
public Callable<ResponseEntity<String>> test(@RequestParam(...) Boolean bbb) {
return new Callable<ResponseEntity<String>>() {
@Override
public ResponseEntity<String> call() throws Exception {
try {
<POTENTIALLY LONG 3RD-PARTY FUNCTION CALL HERE>
.....
} catch (Exception e) {
return new ResponseEntity<String>("..." }", HttpStatus.BAD_REQUEST);
}
}
};
}
Thank you.
Upvotes: 0
Views: 1014
Reputation: 140417
In the end, to exercise a timeout, you are looking at multiple threads working together. The problem with Java threads is this: you aren't supposed to kill them. See here for example: How do you kill a Thread in Java?
In other words: if you intend to really control 3rd party code and be able to kill it, then threads won't do. You could try and see if using thread.stop() works "reliably enough" for you. And of course, you can see how simply interrupting a thread that runs your method leads to. You definitely have to work directly with bare metal threads.
If all of that fails... what would definitely work: run that function call in its own dedicated jvm! You can always kill a child process.
The downside of course: now you need to worry about intra process communication and how to get your data to that function and back from it!
Upvotes: 1