Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ExecutorService: should I put a lock before to use execute?

I have a class organized as follows:

public class MyClass {

   ExecutorService pool;

   public MyClass(){
     pool = ... //inited by a class that implements ExecutorService
   }

   public final void submit(Runnable run){
        pool.execute(run);
   }
}

Is the method submit thread safe or I should use a Lock-based system? E.g.

   ReentrantLock look  = new ReentrantLock();

   public final void submit(Runnable run){
        lock.lock();
        try{ pool.execute(run); } finally{lock.unlock();}
   }
like image 328
mat_boy Avatar asked Jan 13 '23 15:01

mat_boy


1 Answers

No you don't need the lock when calling ExecutorService#submit.

Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().

or when calling Executor#execute:

Memory consistency effects: Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread.

like image 160
assylias Avatar answered Jan 22 '23 03:01

assylias