4

I have a java application "with history" and it uses WeakReferences for caching. I made several heapdumps and saw that all of them contains a lot of objects with weak references (10%-15% of heap size, ~1.2GB).

  • Does it mean that weak references produce memory pressure on JVM?
  • And forces a FullGC with stop-the-world pauses?

P.S. I know that WeakReference produces performance penalty for GC for CMS, because it makes algorithm harder. But did somebody see a paper or some official information about it? I found only this SO post.

Community
  • 1
  • 1
Jimilian
  • 3,859
  • 30
  • 33

2 Answers2

1

Object Computing, Inc. did a presentation on this that I've found useful in the past. Here's an excerpt:

Kinds of Object References

  • Strong references
  • SoftReference
  • GC’ed any time after there are no strong references to the referent, but is typically retained until memory is low
  • can be used to implement caches of objects that can be recreated if needed

WeakRefernence

  • GC’ed any time after there are no strong or soft references to the referent
  • often used for “canonical mappings” where each object has a unique identifier (one-to-one), and in collections of “listeners”

"For soft and weak references, the get returns null method when the referent object has been GC’ed."

SOURCE: http://java.ociweb.com/mark/other-presentations/JavaGC.pdf

That seems to suggest SoftReference is the go to choice for cached objects.

In practice I have used Guava caching APIs and let it manage the details: https://github.com/google/guava/wiki/CachesExplained

Alain O'Dea
  • 21,033
  • 1
  • 58
  • 84
  • Thanks for your answer, but it doesn't answer on my question :) For cache I prefer [Encache](http://www.ehcache.org), because it has a lot of options, Beans, statistics, etc. But in case of this topic I'm interesting in question **when** GC removes objects with WeakReference. – Jimilian Nov 12 '15 at 20:21
1

Does it mean that weak references produce memory pressure on JVM?

No. Weak references don't affect GC at all. They just give you a way to track it.

And forces a FullGC with stop-the-world pauses?

No.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • So from GC performance perspective there is no difference between using and not using WeakReference? And removing WeakReference doesn't increase performance? – Jimilian Nov 12 '15 at 20:33
  • And do you know when GC cleans up object with WeakReference? For example, in CMS algorithm. – Jimilian Nov 12 '15 at 20:35
  • I've already answered your first question. The answer to the second question is basically 'whenever it likes'. – user207421 Nov 12 '15 at 22:15