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
  • 6,787
  • 10
  • 46
  • 87
王子1986
  • 3,019
  • 4
  • 31
  • 43
  • If you are talking about `submit` then it only throws `RuntimeExceptions` see https://stackoverflow.com/questions/6115896/java-checked-vs-unchecked-exception-explanation – Scary Wombat Sep 07 '18 at 00:15
  • Read from somewhere that people say I should handle exceptions in threads. Like this article https://medium.com/@aozturk/how-to-handle-uncaught-exceptions-in-java-abf819347906 – 王子1986 Sep 07 '18 at 00:17
  • where? what people? Did you understand my comment? – Scary Wombat Sep 07 '18 at 00:18
  • @NathanHughes will this handled exception kill the application eventually? – 王子1986 Sep 07 '18 at 00:30
  • No. It’s just that the application does more work than it should have to. – Nathan Hughes Sep 07 '18 at 00:33
  • @NathanHughes hmmm, what’s the additional work does the application do? I tried to monitor application threads with visualvm. The only difference I can notice is the thread status , one is monitor , another is idle. – 王子1986 Sep 07 '18 at 00:39
  • Threads are OS resources. The application has to obtain replacements when they get terminated. With a toy example you won’t see a problem. – Nathan Hughes Sep 07 '18 at 00:41
  • @NathanHughes use a big block try catch or just leave the code like that, which one is more practical? Threads creation seems very cheap. – 王子1986 Sep 07 '18 at 00:45

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.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
0

You supposed to keep the return value Future

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

Dapeng
  • 1,704
  • 13
  • 25