Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make thread go to finally after certain time has passed

I have a thread which may get stuck and keep running forever. Thus after a certain amount of time, I would like it to stop executing, go to the finally method to do cleanup, and then die. How would I go about doing this safely? Thanks.

My first thought on how to do this was to make a child thread and have that sleep and then do the cleanup. But then when the parent thread is still trying to run and it can't so it outputs an error.

like image 558
user760220 Avatar asked Oct 21 '22 04:10

user760220


1 Answers

Refactor your code into a Callable and use an ExecutorService to get a Future. Then use get with a timeout, which throws a TimeoutException if not done by then. See https://stackoverflow.com/a/2275596/53897 for a full example.

like image 116
Thorbjørn Ravn Andersen Avatar answered Oct 24 '22 04:10

Thorbjørn Ravn Andersen