Java 是否需要同步ExecutorService.execute()?
我创建了一个枚举单例,如下所示:Java 是否需要同步ExecutorService.execute()?,java,multithreading,asynchronous,threadpoolexecutor,Java,Multithreading,Asynchronous,Threadpoolexecutor,我创建了一个枚举单例,如下所示: public enum Logging { INSTANCE; ExecutorService pool = Executors.newFixedThreadPool(4); } 现在,我使用这个池在特定情况下异步记录日志。 调用代码如下所示: Logging.INSTANCE.execute(new MyRunnable("LogType.A",logData)); public synchronized void sub
public enum Logging {
INSTANCE;
ExecutorService pool = Executors.newFixedThreadPool(4);
}
现在,我使用这个池在特定情况下异步记录日志。
调用代码如下所示:
Logging.INSTANCE.execute(new MyRunnable("LogType.A",logData));
public synchronized void submitTask(Runnable task) {
executor.execute(task);
}
MyRunnable对象的Run方法很简单,如下所示:
public class MyRunnable {
public MyRunnable(LogType logType,String logData){
this.logType=logType;
this.logData=logData;
}
public void run() {
switch(logType) {
case A:
logData(Logger.getLogger(A_LOG),logData);
break;
case B:
logData(Logger.getLogger(B_LOG,logData));
break;
}
private void logData (Logger logger,String logdata) {
if(some condition)
logger.info(logdata);
else
do something else;
}
}
现在我的问题是,如果我用多个线程向队列提交大量请求,我是否会面临任何并发问题?executor.execute(任务)是否已同步,或者我是否需要在同步方法(在日志记录枚举中)中包装execute方法,然后调用该方法,如下所示:
Logging.INSTANCE.execute(new MyRunnable("LogType.A",logData));
public synchronized void submitTask(Runnable task) {
executor.execute(task);
}
现在我的问题是,如果我提交,我会面临任何并发问题吗
对具有多个线程的队列的大量请求
否不需要使用同步
public synchronized void submitTask(Runnable task) {
executor.execute(task);
}
public enum Logger {
INSTANCE;
ExecutorService pool = Executors.newFixedThreadPool(4);
public void log(String logType, String logData){
//you internally create a instance of your runnable and not leave on caller to create instance
pool.execute(new MyRunnable(logType, logData));
}
}
即使在这里,也可以安全地删除同步
public synchronized void submitTask(Runnable task) {
executor.execute(task);
}
public enum Logger {
INSTANCE;
ExecutorService pool = Executors.newFixedThreadPool(4);
public void log(String logType, String logData){
//you internally create a instance of your runnable and not leave on caller to create instance
pool.execute(new MyRunnable(logType, logData));
}
}
六羟甲基三聚氰胺六甲醚。。。可能是代码片段来自不同版本的代码吗?如果
logData()
或logSData()
不是线程安全的,您将遇到并发问题。但是使用线程池是毫无意义的。你的执行器应该是最终的;目前,没有任何东西可以阻止外部方法将其设置为null
@fge感谢您指出最后一件事。@Axel我已经用logData方法更新了问题。它只是登录到相应的日志文件中。您仍然认为会出现并发问题吗?