Hi all,
From
this thread
, I saw in
section 11.13 of the Book of Vaadin
, that you recommend loggers be declared static. It’s my understanding that this leads directly to memory leaks, though it’s not a well-known issue. It’s hard for me to find a good reference about this now, but here’s one page that talks about a similar issue (in this example the leak is through Level and not Logger):
https://blogs.oracle.com/fkieviet/entry/classloader_leaks_the_dreaded_java
(Frantic searching…) Oh, here’s another one, but it talks about a slightly different issue:
http://wiki.apache.org/commons/Logging/StaticLog
I used to have this one great article about it, but of course I can’t find it now. Grrr. Anyway…
There’s no problem with declaring some random object static in a class in a web/EE app
as long as the container does not also have a handle to that object
. With a logger obtained from Logger.getLogger(“example”), your class’ classloader has a handle to that logger, and so does the JVM through a map of weak references. So when the application is undeployed, the instances of the class go away but the classloader cannot be garbage collected because it has a non-weak reference to an object that can’t be GC’ed itself. Someone on the Sun JDK told me a couple years ago that this would be fixed in Java 7, but I don’t know anything else about that. (To be completely honest, I can’t explain now why this is different from instances having non-static references, but that may be that it’s Friday.)
The simple fix is to not declare loggers as static. I’ve read many places online that this means you’re creating lots of loggers, but that’s simply not true. Logger.getLogger(String) only creates one logger for each name, and returns a reference to it whenever you call getLogger(). Sure, there’s a very slight hit for the map lookup, but that’s trivial compared to running into
the root of all evil
(I’m referring to his quote, not the person!).
At least, this is my memory of the problem. I wish I could find some better references on it, but I remember this from my days working on the GlassFish team, and the consensus was that it’s ok for the container to use static loggers, but the applications never should. You’ll have to go through a lot of deployment cycles probably to run into the memory issue, but it’s simple enough to avoid the issue. From my experience, most code out there does this wrong, but it works fine up to a point. Then you restart the server…
Cheers,
Bobby
p.s. I suppose maybe, possibly, you could use a static weak reference to a logger in your code, but that’s just silly.