Is it safe to use singleton ExecutorService
and multiple instances of CompletionService
using the same thread pool?
CompletionService<Object> collector = new ExecutorCompletionService<Object>(threadPool);
So, there will be multiple threads creating instances like above, 'collector' with one singleton threadPool.
For ThreadPoolExecutor the answer is simply yes. ExecutorService does not mandate or otherwise guarantee that all implementations are thread-safe, and it cannot as it is an interface. These types of contracts are outside of the scope of a Java interface.
When finished using an ExecutorService , you need to shut it down explicitly. From its javadoc: "An unused ExecutorService should be shut down to allow reclamation of its resources." Calling shutdown initiates a gradual and orderly shutdown.
ExecutorService abstracts away many of the complexities associated with the lower-level abstractions like raw Thread . It provides mechanisms for safely starting, closing down, submitting, executing, and blocking on the successful or abrupt termination of tasks (expressed as Runnable or Callable ).
Right, this ExecutorService blocks tasks on submission without blocking caller thread. Job just getting submitted and will be processed asynchronously when there will be enough system resources for it.
It will be fine. Each instance of ExecutorCompletionService
maintains its own queue of completed tasks and just uses the underlying Executor
to process each task.
The tasks may interfere with each other performance-wise if the number of completion services is large and the thread pool has an upper limit but that won't affect the correctness of the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With