gpt4 book ai didi

java - 我需要同步ExecutorService.execute()吗?

转载 作者:行者123 更新时间:2023-11-30 04:20:36 27 4
gpt4 key购买 nike

我创建了一个枚举单例,如下所示:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com