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

标签 java multithreading asynchronous threadpoolexecutor

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

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/

相关文章:

java - Java Enums 之间可以共享一些通用的代码吗?

java - 如何使用随机选择获取列表中元素的文本?

Java pow BigInteger 实现

multithreading - Entity Framework 和多线程

c - Linux 中对 pthread_create 的 undefined reference

multithreading - C#IE BHO : Do work asynchroniously while keeping to the same thread?

java - 此代码会造成潜在的内存泄漏吗?

objective-c - 在 Objective-c 中,如果父方法在子方法执行时释放了子方法,会发生什么?

javascript - 是否可以实现同步使用非阻塞 setTimeout 的函数?

asynchronous - 如何使JQuery文件上传插件对上传中的所有文件仅调用后端一次?