I am trying to demonstrate an "anytime algorithm" - an algorithm that can be stopped at any time and returns its current result. The demo algorithm just returns some mathematical function of i, where i is increasing. It chcecks whether it is interrupted, and if so, returns the current value:
static int algorithm(int n) {
int bestSoFar = 0;
for (int i=0; i<n; ++i) {
if (Thread.interrupted())
break;
bestSoFar = (int)Math.pow(i, 0.3);
}
return bestSoFar;
}
In the main program, I use it like this:
Runnable task = () -> {
Instant start = Instant.now();
int bestSoFar = algorithm(1000000000);
double durationInMillis = Duration.between(start, Instant.now()).toMillis();
System.out.println("after "+durationInMillis+" ms, the result is "+bestSoFar);
};
Thread t = new Thread(task);
t.start();
Thread.sleep(1);
t.interrupt();
t = new Thread(task);
t.start();
Thread.sleep(10);
t.interrupt();
t = new Thread(task);
t.start();
Thread.sleep(100);
t.interrupt();
t = new Thread(task);
t.start();
Thread.sleep(1000);
t.interrupt();
}
}
When I run this program, I get the following input:
after 0.0 ms, the result is 7
after 10.0 ms, the result is 36
after 100.0 ms, the result is 85
after 21952.0 ms, the result is 501
I.e, the first three threads are really interrupted when I tell them to, but the last thread is not interrupted after 1 second - it continues working for almost 22 seconds. Why does this happen?
EDIT: I get similar results using Future.get with a timeout. In this code:
Instant start = Instant.now();
ExecutorService executor = Executors.newCachedThreadPool();
Future<?> future = executor.submit(task);
try {
future.get(800, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
future.cancel(true);
double durationInMillis = Duration.between(start, Instant.now()).toMillis();
System.out.println("Timeout after "+durationInMillis+" [ms]");
}
if the timeout is at most 800 then everything works find and it prints something like "Timeout after 806.0 [ms]". But if the timeout is 900 it prints "Timeout after 5084.0 [ms]".
EDIT 2: my computer has 4 cores. The program rusn on Open JDK 8.