Why does the ExecutorService interface not implement AutoCloseable?

前端 未结 3 1767
北恋
北恋 2020-12-29 04:01

Failing to call shutdown() on a thread executor will result in a never terminating application.

Best practice to shut down the ExecutorService is this:

3条回答
  •  一个人的身影
    2020-12-29 04:42

    This is a mediocre workaround

    ExecutorService service = Executors.newSingleThreadExecutor();
    try (Closeable close = service::shutdown) {
    
    }
    

    Or, if the checked exception bothers you, you could write:

    interface MyCloseable extends AutoCloseable {
        void close();
    }
    

    And then

    ExecutorService service = Executors.newSingleThreadExecutor();
    try (MyCloseable close = service::shutdown) {
    
    }
    

    Of course, you must never ever put anything between the assignment and the try statement, nor use the service local variable after the try statement.

    Given the caveats, just use finally instead.

提交回复
热议问题