How to stop a time-limited process

I think this topic may not be accurate enough, but I really don’t know how to describe it very briefly ...

I want to do the following: I have a process that does some analysis (in Java) and tries to give a return value, but the whole analysis has a time limit, for example 10 seconds

If the analysis gives a result within 10 s, return the result; otherwise, once before reaching 10 s, stop the process and return a dummy value

I am new to this area, any suggestions would be welcome.

+3
source share
4 answers

FutureTask ( get() ). , .

cancel() , true to, .

Object result = DUMMY;
try {
   result = futureTask.get(5, TimeOut.SECONDS);
}
catch (TimeoutException e) {
   futureTask.cancel(true);
}
+2

(java.util.Timer), , , , .

, 10 . , . . stop() , , .

+1

AI , Minimax, 5 . , , , System.currentTimeMillis().

, , , , , .

Otherwise, use FutureTask and call the get method on it with your timeout. One thing that Brian didn't mention is that your processing code should check to see if it interrupted periodically in order to actually stop execution earlier.

0
source

Source: https://habr.com/ru/post/1713398/


All Articles