Reputation: 2004
I have created a Enum singleton as below:
public enum Logging {
INSTANCE;
ExecutorService pool = Executors.newFixedThreadPool(4);
}
Now I am using this pool for logging asynchronously in specific cases. Calling code is like below:
Logging.INSTANCE.execute(new MyRunnable("LogType.A",logData));
Run method of the MyRunnable object is simple like below:
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;
}
}
Now my query is will I face any concurrency issues if I am submitting lot of requests to the queue with multiple threads ?Isn't executor.execute(task) already synchronized or Do I need to wrap execute method in the synchronized method(in Logging enum) and than call that method like below:
public synchronized void submitTask(Runnable task) {
executor.execute(task);
}
Upvotes: 1
Views: 5168
Reputation: 41945
Now my query is will I face any concurrency issues if I am submitting lot of requests to the queue with multiple threads ?
No there is no need of using synchronized.
public synchronized void submitTask(Runnable task) {
executor.execute(task);
}
Even here it is safe to remove synchronized.
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));
}
}
Upvotes: 2