Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use singleton ExecutorService

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.

like image 481
ankitjaininfo Avatar asked Aug 23 '11 12:08

ankitjaininfo


People also ask

Is ExecutorService thread safe?

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.

Should ExecutorService be shutdown?

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.

What are the advantages of using ExecutorService instead of creating threads directly?

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 ).

Is ExecutorService submit blocking?

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.


1 Answers

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.

like image 171
Mike Q Avatar answered Oct 15 '22 20:10

Mike Q