0

I have this code:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Boolean> f = executor.submit(() -> {
    if (true) {
        while (true);
    }
    return false;
});
try {
    System.out.println(f.get(10, TimeUnit.MILLISECONDS));
}
catch (InterruptedException | ExecutionException | TimeoutException e) {
    throw e;
}

While I'm running the program, I get the Exception like I should, but the while loop continues to run and the program does not stop.
I tried executor.shutdown(), executor.shutdownNow(), f.cancel(true) and more.
Does anyone have any idea? I'm trying to solve this for three days.

Ziv Sdeor
  • 33
  • 7

1 Answers1

4

You shouldn't be using a busy loop, but the way you'd do that is to stop if the thread has been interrupted:

while (!Thread.interrupted()) {
    // do something
}

Rather than use a busy loop, your thread should be waiting on a signal or an event. Or even polling at a set interval. A busy loop like the one you describe will simply use up the CPU.

For instance, you can simply call wait on any object, and your thread will be woken up upon being interrupted.

try {
    (new Object()).wait();
} catch (InterruptedException e) {
    // Interrupted
}

See here for a discussion of thread signalling: http://tutorials.jenkov.com/java-concurrency/thread-signaling.html

jspcal
  • 50,847
  • 7
  • 72
  • 76