Weak reference: Difference between revisions

Content deleted Content added
Java: The parameter passed to weak and strong constructor should be consistent.
clarity
Line 2:
 
==Uses==
Weak references have a number of common use cases. When using [[reference counting]] garbage collection, weak references can break [[reference cycle]]s, by using a weak reference for a link in the cycle. When one has an [[associative array]] (mapping, hash map) whose keys are (references to) objects, for example to hold auxiliary valuedata about objects, using weak references for the keys avoids keeping the objects alive just because of their use as a key. When one has an object where other objects are registered, such as in the [[observer pattern]] (particularly in [[event handling]]), if a strong reference is kept, objects must be explicitly unregistered, otherwise a memory leak occurs (the [[lapsed listener problem]]), while a weak reference removes the need to unregister. When holding cached data that can be recreated if necessary, weak references allow the cache to be reclaimed, effectively producing discardable memory. This last case (a cache) is distinct from others, as it is preferable that the objects only be garbage collected if necessary, and there is thus a need for finer distinctions within weak references, here a stronger form of a weak reference. In many cases weak references do not need to be directly used, instead simply using a weak array or other [[Container (abstract data type)|container]] whose keys or values are weak references.
 
==Garbage collection==