Is ExecutorService (specifically ThreadPoolExecutor) thread safe?

后端 未结 6 2041
长情又很酷
长情又很酷 2020-11-27 05:26

Does the ExecutorService guarantee thread safety ?

I\'ll be submitting jobs from different threads to the same ThreadPoolExecutor, do I have to synchro

6条回答
  •  半阙折子戏
    2020-11-27 05:55

    Contrary to what the answer by Luke Usherwood claims, it is not implied by the documentation that ExecutorService implementations are guaranteed to be thread-safe. As to the question of ThreadPoolExecutor specifically, see other answers.

    Yes, a happens-before relationship is specified, but this does not imply anything about the thread-safety of the methods themselves, as commented by Miles. In Luke Usherwood's answer it is stated that the former is sufficient to prove the latter but no actual argument is made.

    "Thread-safety" can mean various things, but here is a simple counter-example of an Executor (not ExecutorService but it makes no difference) that trivially meets the required happens-before relationship but is not thread-safe because of unsynchronized access to the count field.

    class CountingDirectExecutor implements Executor {
    
        private int count = 0;
    
        public int getExecutedTaskCount() {
            return count;
        }
    
        public void execute(Runnable command) {
            command.run();
        }
    }
    

    Disclaimer: I'm no expert and I found this question because I was searching for the answer myself.

提交回复
热议问题