【问题标题】:Do I need to synchronize ExecutorService.execute()?我需要同步 ExecutorService.execute() 吗?
【发布时间】:2013-06-18 06:42:39
【问题描述】:

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

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);     
}

【问题讨论】:

  • hmmm ...可能是sn-ps来自您的代码的不同版本吗?如果logData()logSData() 不是线程安全的,您将遇到并发问题。但是使用线程池就没有任何意义了。
  • 您的executor 应该是final;目前,没有什么能阻止外部方法将其设置为 null!
  • @fge 感谢您指出最后一件事。
  • @Axel 我已经用 logData 方法更新了问题。它只是登录到相应的 logFile。你还认为会有并发问题吗?

标签: java multithreading asynchronous threadpoolexecutor


【解决方案1】:

现在我的查询是,如果我提交,我是否会面临任何并发问题 多线程队列的大量请求?

不需要使用同步。

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));
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多