问题
I'm profiling my application using VisualVM and I see that the heap size increased by about 7MB in about 3 days. When I use memory sampler, I also see that java.lang.ref.WeakReference
is in the top five for the instances number. The number of WeakReference
is increasing and GC has almost no effect.
Any idea?
回答1:
You do not have a memory leak.
Java's GC only runs when the heap is full (actually is a bit more complicated since the heap itself is divided into generations, but anyway), so unless you are filling the heap (which is very unlikely since 7Mb is too little memory for any heap) you can't tell wether you have a leak or not.
WeakReferences
are small wrappers that actually help preventing memory leaks by marking the objet they reference as elegible for GC. My guess is that you're including some kind of cache library that creates a bunch of these, and since the heap still has plenty of room there's no need to garbage collect them.
Again, unless you see that the GC runs often and your heap size still increases I wouldn't worry about memory issues.
Here's a great article on this matter
回答2:
WeakReferences are the among first to get collected in case the JVM runs a full GC, however, they must not be strongly/ softly reachable (no strong/ soft reference must be holding a reference to it). I am usually least worried about WeakReferences, they do get GC-ed eventually. You should check your GC cycles (jstat) and see if even GC is not claiming these references. Also, please do not extrapolate the leak, your application may not necessarily grow its memory consumption in the next few days. I would suggest running a long (48 hr?) performance test with a significant load on a non production environment and see if you run into memory issues.
回答3:
VisualVM uses resources in the system. This is one of its weakness compared with commercial profilers. As such small differences cannot be easily seen with VisualVM because it creates its own noise.
Lets say you have a leak of 7 MB in 3 days (which I doubt). How much times is it worth you spending to fix it? 16 GB of memory costs about $100 so 7 MB is worth about 5 cents, or about 3 seconds of your time. I would worry about it more if it were larger, much larger.
来源:https://stackoverflow.com/questions/7944148/weakreference-and-memory-leaks