I have a java command line tool that turns logging off at the very beginning, then parses the command line and later possibly turns logging on again, depending on the result of command line processing.
The main method begins like this:
public static void main(final String[] args){
java.util.logging.LogManager.getLogManager().reset();
java.util.logging.Logger globalLogger = java.util.logging.Logger
.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
globalLogger.setLevel(java.util.logging.Level.OFF);
[... parse command line and possibly turn logging back on]
Now Findbugs give a "Troubling" warning that says:
Changes to logger could be lost in com.bmw.fnw.DBMainDialog.main(String[])
From the Find Bugs Description I understand that the logger could possilby on when it shouldn't.
What can I do to properly turn the logger off?
Just hold a strong reference to the logger as long as you need it (probably for the lifetime of your program).
The link you gave already explains why: In OpenJDk, the logManager internally only keeps weak references. So the logger becomes eligible for garbage collection as soon as there is no strong reference. So you set the configuration, but don't hold a strong reference. It may be garbage collected. When you get the Logger again, a new one is instantiated. Garbage collection is prevented by holding a strong reference.
Are you using OpenJDK as stated by the Find Bugs description?
Whatever since they talk about Weak Reference, what comes to my mind is that you may create a static reference somewhere to this logger, to avoid losing it during garbage collection.
To test the problem you may call yourself the garbage collector in your code, see if it changes anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With