我创建了一个枚举单例,如下所示:
public enum Logging {
INSTANCE;
ExecutorService pool = Executors.newFixedThreadPool(4);
}
现在我使用这个池在特定情况下进行异步日志记录。 调用代码如下:
Logging.INSTANCE.execute(new MyRunnable("LogType.A",logData));
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(task) 是否已经同步,或者我是否需要在同步方法中包装执行方法(在 Logging 枚举中)然后调用该方法,如下所示:
public synchronized void submitTask(Runnable task) {
executor.execute(task);
}
最佳答案
Now my query is will I face any concurrency issues if I am submitting lot of requests to the queue with multiple threads ?
否不需要使用同步。
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));
}
}
关于java - 我需要同步ExecutorService.execute()吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17162150/