Java – is it valid to get the logger from the static final variable initializer?

We have many class codes, and they have some templates as follows:

private static Logger logger = null;

private static Logger getLogger() {
  if (logger == null) {
    logger = Logger.getLogger(MyClass.class);
  }
  return logger;
}

The idea is that the class can record the debugging content in the logger The first code that needs to record something calls getlogger () and makes the logger exist

There are a few things I don't like about this model First, the singleton getlogger () is out of sync and synchronizes it, and being correct will burden each subsequent call for no reason

I really hope to compress it to this:

private static final Logger logger = Logger.getLogger(MyClass.class);

Then I can reference the logger directly, even without a separate getter

My concern is that by doing so, I will create a logger when loading the class, even if I have never called the logger I have 10000 strange classes that call getlogger (), so how many logger instances do I actually create here? If my log4j attribute contains some Appenders, I just refer to the same logger again and again, or am I creating 10000 such things?

Solution

If you use the default log4j configuration (i.e. default loggerrepository, defaultcategoryfactory, etc.), you will create 10'000 logger instances How much memory do they consume? No one knows this except God and your probe My guess is that only the latter one will tell you

If the memory consumption is too large for your environment, move the logger initialization to the static inner class, as shown below:

static class LoggerHolder {
  static Logger logger = Logger.getLogger(MyClass.class);
}

private static Logger getLogger() {
  return LoggerHolder.logger;
}

In this way, an instance of the logger will be created only on the first getlogger call This technique is called initialization on demand holder (IODH), which is thread safe and has no synchronization overhead

Can I give you an off topic suggestion? Consider replacing log4j with a combination of slf4j logback libraries They were written by the same author and described as "the successor of the popular log4j project, where log4j leaves" You can read more in this so thread

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>