Java ExecutorService:我应该在使用execute之前加锁吗? [英] Java ExecutorService: should I put a lock before to use execute?
问题描述
我有一个课程组织如下:
public class MyClass {ExecutorService 池;公共 MyClass(){pool = ...//由一个实现 ExecutorService 的类初始化}公共最终无效提交(可运行运行){池.执行(运行);}}
submit
方法是线程安全的还是我应该使用基于 Lock
的系统?例如
ReentrantLock look = new ReentrantLock();公共最终无效提交(可运行运行){锁.lock();尝试{池.执行(运行);} 最后{lock.unlock();}}
不,调用 ExecutorService#submit.
<块引用>内存一致性影响:在将 Runnable 或 Callable 任务提交给 ExecutorService 之前线程中的操作发生在该任务采取的任何操作之前,而后者反过来发生在通过 Future.get() 检索结果之前.
或在调用 Executor#execute 时:><块引用>
内存一致性影响:在将 Runnable 对象提交给 Executor 之前线程中的操作发生在其执行开始之前,可能在另一个线程中.
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();}
}
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.
这篇关于Java ExecutorService:我应该在使用execute之前加锁吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!