Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a process with time constraints

I think the topic might not be accurate enough, but I really don't know how to describe it in a very brief way...

What I want to do is as follows: I have a process running some analysis (in Java) and trying to give a return value, but the whole analysis has a time constraint, say 10 seconds

If the analysis gives a result within 10s, return the result; else, times up when reaching 10s, stop the process and return a dummy value

I am a newbie in this field, any suggestions will be welcomed.

like image 533
Lily Avatar asked Oct 21 '25 21:10

Lily


1 Answers

You can use FutureTask to create a job and request the result within a particular time (using get() with a timeout). If that time window is breached, then you'll get an exception.

At that point you can then call the cancel() method with the parameter set to true to force an interruption and cancel the underlying task.

Object result = DUMMY;
try {
   result = futureTask.get(5, TimeOut.SECONDS);
}
catch (TimeoutException e) {
   futureTask.cancel(true);
}
like image 77
Brian Agnew Avatar answered Oct 23 '25 11:10

Brian Agnew