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?
Overview. ExecutorService is a JDK API that simplifies running tasks in asynchronous mode.
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.
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.
An unused ExecutorService should be shut down to allow reclamation of its resources. Method submit extends base method Executor. execute(java. lang.
ExecutorService has to use a thread safe queue (Which it does by default). This is all that is needed.
No, there is no need to synchronize calls to add() method.
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