I understand what a Java WeakReference is. What I want to know is on which kind of concrete problems it's used normally as a solution. Are there any patterns that include them?
-
You can use it to keep some properties related to an object without preventing the deletion of that object. – Denys Séguret Feb 12 '14 at 13:22
-
1https://weblogs.java.net/blog/2006/05/04/understanding-weak-references (first link on Google) – Christophe Roussy Feb 12 '14 at 13:23
-
1Do not forget you have the stackoverflow wiki of the tag itself: http://stackoverflow.com/tags/weak-references/info – Christophe Roussy Feb 12 '14 at 13:25
-
1@ChristopheRoussy lol. I wrote that tag wiki, should have remembered and linked to it instead of doing an answer. :D – Tim B Feb 12 '14 at 13:28
-
1See also: http://stackoverflow.com/questions/11231565/why-do-we-need-weak-reference-in-java – assylias Feb 12 '14 at 13:31
1 Answers
WeakReference
and SoftReference
are used when you want to keep something around in case you need it again - but you might not need it and if you do need it you can recreate it.
For example if you have a Cache of information you've fetched from a website, you don't want to constantly re-fetch it but if you need memory you can always drop something you haven't used for a while and get it back again if you do need it.
SoftReferences
in particular are useful for this sort of caching as it tells the GarbageCollector not to get rid of the objects unless it really needs to free up the memory.
WeakReference
on the other hand the GC can clean up as soon as it likes.
I've used them before combined with a factory pattern. Keep a SoftReference
to objects when you create them in the factory. If they are asked for again then return the already-created object. If they don't exist or have been garbage collected then create them, return them, and keep a SoftReference
inside the factory.

- 40,716
- 16
- 83
- 128
-
-
-
Solely relying on Weak/SoftReference for caching [is generally not a good idea as it may lead to poor performance](http://stackoverflow.com/a/11232117/829571) - it's often better to use an explicit caching strategy. – assylias Feb 12 '14 at 13:35