Is ExecutorService (specifically ThreadPoolExecutor) thread safe?

后端 未结 6 2025
长情又很酷
长情又很酷 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:44

    Your question is rather open-ended: All the ExecutorService interface does is guarantee that some thread somewhere will process the submitted Runnable or Callable instance.

    If the submitted Runnable / Callable references a shared data structure that is accessible from other Runnable / Callables instances (potentially being processed simulataneously by different threads), then it is your responsibility to ensure thread safety across this data structure.

    To answer the second part of your question, yes you will have access to the ThreadPoolExecutor before submitting any tasks; e.g.

    BlockingQueue workQ = new LinkedBlockingQueue();
    ExecutorService execService = new ThreadPoolExecutor(4, 4, 0L, TimeUnit.SECONDS, workQ);
    ...
    execService.submit(new Callable(...));
    

    EDIT

    Based on Brian's comment and in case I've misunderstood your question: Submission of tasks from multiple producer threads to the ExecutorService will typically be thread-safe (despite not being mentioned explicitly in the interface's API as far as I can tell). Any implementation that didn't offer thread safety would be useless in a multi-threaded environment (as multiple producers / multiple consumers is a fairly common paradigm), and this is specifically what ExecutorService (and the rest of java.util.concurrent) was designed for.

提交回复
热议问题