How do I know I have leak in Java?
I'm running my application using the Netbeans profiler and the char type seem very a开发者_运维知识库ctive. I see the generations number reaching all the way up to 180 generations and dropping down to 80 and going back up it seems to average 160 generations.
It's hard to tell because it is a custom TCP/IP server app that uses JDBC, Hibernate and connections pools.
1- If the generation numbers goes up and down, can assume that it's ok? Only if it keeps going up and up and never goes down then there a potential problem?
2- The Netbeans generation graph just keeps going up. At the end of my stress test it was at 20000 generations. Is the graph the total over time? I'm confused because when looking at live results, the generations, as mentioned above, go up and down for the char type.
3- By manually invoking the garbage collector from the profiler, the memory seems to drop back down. So I figure that's also ok?
- 1) Yes. It goes up due to all the constructed instances, and down when the garbage collector starts.
- 3) Well, yes, you do 1 by hand. It shouldn't be necessary though.
A memory leak can be identified by looking at the minimum amount over time. Every time the GC runs it should be almost the same if you keep running the same code.
It may grow a bit if you enter different parts of the code, as classes get loaded and possibly statics get constructed.
As it is, it is very hard to identify a leak without knowing the code paths taken. I've had leaks which don't manifest until about 100000 messages were processed, and only came problematic after a few weeks running.
Also see This SO question on identifying those leaks.
The way I usually approach a suspected memory leak is:
- let the application run for a while, in a production environment (not your IDE)
- trigger the application to write a Java heapdump
- use the IBM alphaworks HeapAnalyzer to inspect and look for possible problem spots
Memory that can't be cleaned up by the GC will eventually make it into the old generation and then perm space. That's also where .class files and the string pool go, so don't be alarmed if you see that it's not empty.
You have to be able to distinguish leak stuff from the things that normally end up in perm space. It's not easy.
精彩评论