1

Did I need to handle runtime exception in executorservice? I tried an example in spring boot web application, the code will still execute despite of exception

Here is the code:

@RestController
class WelcomeController {
    ExecutorService es = Executors.newSingleThreadExecutor();

    @GetMapping("/sayhi")
    public String sayHi() {
        es.submit(() -> {
            System.out.println("hello");

            int a = 0;
            if (10 / a == 1) {

            }
        });

        return "hi";
    }
}
alltej
  • 5,998
  • 7
  • 39
  • 73
王子1986
  • 2,417
  • 3
  • 26
  • 41

2 Answers2

1

When an exception is thrown in one thread it doesn’t propagate to other threads unless you do something to make it do that (like using a Future). Here the thread causes an exception and dies, but the rest of the program isn’t affected.

The executor creates a replacement for the lost thread, see the api doc:

Creates an Executor that uses a single worker thread operating off an unbounded queue, and uses the provided ThreadFactory to create a new thread when needed. Unlike the otherwise equivalent newFixedThreadPool(1, threadFactory) the returned executor is guaranteed not to be reconfigurable to use additional threads.

It would seem to me like a good idea to have tasks handle exceptions that they cause. Otherwise the thread dies and the pool has to start a new one to replace it. This is basically what the article linked in the comments says.

0

You supposed to keep the return value Future

and use Future.get() to interogate if there was an unhandled Exception

Dapeng
  • 1,670
  • 13
  • 25