Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Synchronize an ExecutorService necessary?

I have a class containing an ExecutorService that can be shared between threads:

class MyExecutor {
    ExecutorService e = Executors.newSingleThreadExecutor();
    ....
    .... 
    public void add(Runnable r) {
         e.executre(r);
    } 
}

Is it necessary to synchronize the ExecutorService object in the add method since the add method can be called from differens threads or is the ExecutorService thread safe?

like image 970
Rox Avatar asked Dec 09 '11 13:12

Rox


People also ask

Is ExecutorService synchronous?

Overview. ExecutorService is a JDK API that simplifies running tasks in asynchronous mode.

Why is it necessary to synchronize threads?

Synchronization is the cooperative act of two or more threads that ensures that each thread reaches a known point of operation in relationship to other threads before continuing. Attempting to share resources without correctly using synchronization is the most common cause of damage to application data.

Why is synchronization necessary in Java?

Synchronization in java is the capability to control the access of multiple threads to any shared resource. In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results. The synchronization is necessary for reliable communication between threads.

Do we need to close ExecutorService?

An unused ExecutorService should be shut down to allow reclamation of its resources. Method submit extends base method Executor. execute(java. lang.


2 Answers

ExecutorService has to use a thread safe queue (Which it does by default). This is all that is needed.

like image 140
Peter Lawrey Avatar answered Oct 03 '22 02:10

Peter Lawrey


No, there is no need to synchronize calls to add() method.

like image 40
maximdim Avatar answered Oct 03 '22 00:10

maximdim