How to run the thread for the specific amount of time and return some result when time elapse?
The best solution I can think so far is to measure time manually. But maybe there is more elegant, out of the box solution?
I have an algorithm that in each iteration improves previous solution. I'd like to run this code in a separate thread for the predefined amount of time. When the time elapse, the best (the latest) solution should be returned.
Since I want to return the solution, I can't just use Future#get(long timeout, TimeUnit unit)
- it would result in TimeoutException
. The same about interrupting thread after some time from the "controlling" thread - in such case, Future
would be cancelled and returned null
.
My current solution is as follows:
The timer logic:
private class ExecutionTimer {
private final long executionTimeLimit;
private long startTime;
// accepts execution time limit in _miliseconds_
public ExecutionTimer(final int executionTimeLimit) {
this.executionTimeLimit = TimeUnit.MILLISECONDS.toNanos(executionTimeLimit);
}
public void start() {
this.startTime = System.nanoTime();
}
public boolean hasElapsed() {
return (System.nanoTime() - startTime) >= executionTimeLimit;
}
}
...and the worker thread:
private class WorkerThread implements Callable<Double> {
private final ExecutionTimer executionTimer;
public WorkerThread(final int executionTimeLimit) {
this.executionTimer = new ExecutionTimer(executionTimeLimit);
}
@Override
public Double call() throws Exception {
executionTimer.start();
double partialSolution = 0;
while (!executionTimer.hasElapsed()) {
// let's imagine that here solution is improved ;)
partialSolution = new Random().nextDouble();
}
return partialSolution;
}
}
EDIT: The worker thread can work indefinitely without interrupting it from outside - it is fine because algorithm can always improve previous solution (of course after some significant amount of time improvements are relatively small)