Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cost of using weak references in Java

Has anyone researched the runtime costs involved in creating and garbage collecting Java WeakReference objects? Are there any performance issues (e.g. contention) for multi-threaded applications?

EDIT: Obviously the actual answer(s) will be JVM dependent, but general observations are also welcome.

EDIT 2: If anyone has done some benchmarking of the performance, or can point to some benchmarking results, that would be ideal. (Sorry, but the bounty has expired ...)

like image 878
Stephen C Avatar asked Aug 09 '09 03:08

Stephen C


People also ask

What is the use of weak reference in Java?

Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings. Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable.

Why do you need weak references?

Weak Refernce Objects are needed to JVM platform to ensure means against the memory leaks.

How are weak references implemented?

So, weakref is itself an object, when you put weak reference to an object in some container, you actually put reference to weakref object. Each ref-countable object has field to store pointer to its weakref, which is NULL until weakref to that object is actually requested.

What is the difference between strong and weak references in Java?

If you have a strong reference to an object, then the object can never be collected/reclaimed by GC (Garbage Collector). If you only have weak references to an object (with no strong references), then the object will be reclaimed by GC in the very next GC cycle.


1 Answers

WeakReferences have negative impact on CMS garbage collector. As far as I can see from behavior of our server it influences parallel remark phase time. During this phase all app threads are stopped so it's extremely undesirable thing. So you need to be careful with WeakReferences.

like image 155
Vitaly Avatar answered Oct 05 '22 22:10

Vitaly