我以前从未使用过并发库。
public class QueueExecutor {
static final int defaultCorePoolSize = 5;
static final int defaultMaximumPoolSize = 10;
static final long defaultKeepAliveTime = 10;
static final TimeUnit defaultTimeUnit = TimeUnit.MINUTES;
static final BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
private static ThreadPoolExecutor instance;
private QueueExecutor() {
instance = new ThreadPoolExecutor(defaultCorePoolSize, defaultMaximumPoolSize, defaultKeepAliveTime, defaultTimeUnit, workQueue);
}
public static ThreadPoolExecutor getInstance() {
if (instance == null) {
QueueExecutor();
}
return instance;
}
public static add(Runnable runnable){
} instance.execute(runnable);}
我的问题是,如果这个对象在JBoss应用程序容器中运行,我应该同步add和getInstance函数吗?为什么?我认为这些ThreadPoolExecutor已经同步了。
发布于 2011-11-23 01:25:44
我可以说两件事。
instance final (并相应地初始化它)。因为它是静态的,所以只有在类初始化时才会创建它,并且调用该类的唯一时间是getInstance()。如果这样做,则无需担心synchronization.add不需要同步,因为execute方法为您处理所有同步。说到这两点,建议避免在J2EE环境中创建自己的线程。你可以阅读更多here
发布于 2011-11-23 01:32:12
ThreadPoolExecutor已经是thread-safe,但您的类不是。同步getInstance(),或者至少同步正在检查和初始化实例的块。add()不需要同步,因为它只是委托操作,但我更喜欢使用getInstance().execute(runnable),这样您就不会得到NullPointerException。
https://stackoverflow.com/questions/8230816
复制相似问题