Performing a long calculation that returns after a timeout

半城伤御伤魂 提交于 2020-01-06 01:06:07

问题


I want to perform a search using iterative deepening, meaning every time I do it, I go deeper and it takes longer. There is a time limit (2 seconds) to get the best result possible. From what I've researched, the best way to do this is using an ExecutorService, a Future and interrupting it when the time runs out. This is what I have at the moment:

In my main function:

ExecutorService service = Executors.newSingleThreadExecutor();
ab = new AB();
Future<Integer> f = service.submit(ab);
Integer x = 0;
try {
    x = f.get(1990, TimeUnit.MILLISECONDS);
}
catch(TimeoutException e) {
    System.out.println("cancelling future");
    f.cancel(true);
}
catch(Exception e) {
    throw new RuntimeException(e);
}
finally {
    service.shutdown();
}
System.out.println(x);

And the Callable:

public class AB implements Callable<Integer> {

    public AB() {}

    public Integer call() throws Exception {
        Integer x = 0;
        int i = 0;
        while (!Thread.interrupted()) {
            x = doLongComputation(i);
            i++;
        }
        return x;
    }
}

I have two problems:

  1. doLongComputation() isn't being interrupted, the program only checks if Thread.interrupted() is true after it completes the work. Do I need to put checks in doLongComputation() to see if the thread has been interrupted?
  2. Even if I get rid of the doLongComputation(), the main method isn't receiving the value of x. How can I ensure that my program waits for the Callable to "clean up" and return the best x so far?

回答1:


To answer part 1: Yes, you need to have your long task check the interrupted flag. Interruption requires the cooperation of the task being interrupted.

Also you should use Thread.currentThread().isInterrupted() unless you specifically want to clear the interrupt flag. Code that throws (or rethrows) InterruptedException uses Thread#interrupted as a convenient way to both check the flag and clear it, when you're writing a Runnable or Callable this is usually not what you want.

Now to answer part 2: Cancellation isn't what you want here.

Using cancellation to stop the computation and return an intermediate result doesn't work, once you cancel the future you can't retrieve the return value from the get method. What you could do is make each refinement of the computation its own task, so that you submit one task, get the result, then submit the next using the result as a starting point, saving the latest result as you go.

Here's an example I came up with to demonstrate this, calculating successive approximations of a square root using Newton's method. Each iteration is a separate task which gets submitted (using the previous task's approximation) when the previous task completes:

import java.util.concurrent.*;
import java.math.*;

public class IterativeCalculation {

    static class SqrtResult {
        public final BigDecimal value;
        public final Future<SqrtResult> next;
        public SqrtResult(BigDecimal value, Future<SqrtResult> next) {
            this.value = value;
            this.next = next;
        }
    }

    static class SqrtIteration implements Callable<SqrtResult> {
        private final BigDecimal x;
        private final BigDecimal guess;
        private final ExecutorService xs;
        public SqrtIteration(BigDecimal x, BigDecimal guess, ExecutorService xs) {
            this.x = x;
            this.guess = guess; 
            this.xs = xs;
        }

        public SqrtResult call() {
            BigDecimal nextGuess = guess.subtract(guess.pow(2).subtract(x).divide(new BigDecimal(2).multiply(guess), RoundingMode.HALF_EVEN));
            return new SqrtResult(nextGuess, xs.submit(new SqrtIteration(x, nextGuess, xs)));
        }
    }

    public static void main(String[] args) throws Exception {
        long timeLimit = 10000L;
        ExecutorService xs = Executors.newSingleThreadExecutor();
        try {
            long startTime = System.currentTimeMillis();
            Future<SqrtResult> f = xs.submit(new SqrtIteration(new BigDecimal("612.00"), new BigDecimal("10.00"), xs));
            for (int i = 0; System.currentTimeMillis() - startTime < timeLimit; i++) {
                f = f.get().next;                
                System.out.println("iteration=" + i + ", value=" + f.get().value);
            }
            f.cancel(true);
        } finally {
            xs.shutdown();
        }
    }
}


来源:https://stackoverflow.com/questions/35563921/performing-a-long-calculation-that-returns-after-a-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!