If I have a log4j logger in a class that implements Runnable:
MyTask implements Runnable {
private static final Logger log = Logger.getLogger(MyTask.class);
...
}
If I create many instances of this Runnable and submit them to an ExecutorService on a multi-core machine where they run in parallel, and they all write to the static Logger, this seems like there is a risk of contention. A better pattern seems to be:
MyTask implements Runnable {
private final Logger log;
MyTask(String name) {
log = Logger.getLogger(name);
}
...
}
So my question… is this a pattern you have used or found necessary as at the moment I am purely hypothesising?
Thanks
It is very typical to share a static class logger among many threads. Typically the logger has an underlying
PrintStreamwhich is already synchronized, so creating more than oneLoggeris unnecessary and wasteful.