What Is a Weak Reference?
In computer programming, a weak reference, as opposed to a strong reference, is a reference that cannot guarantee that the object it references will not be recycled by the garbage collector. An object that is only referenced by a weak reference is considered inaccessible (or weakly accessible) and may therefore be recycled at any time. Some languages equipped with garbage collection mechanisms, such as Java, C #, Python, Perl, Lisp, etc., support weak references to varying degrees.
- Garbage collection is used to clean up objects that are no longer used, thereby reducing
- Some languages contain weak references with multiple strengths. E.g
- Weak references can be used in applications to maintain a list of currently referenced objects. The list must be weakly referenced to those objects, or once the objects are added to the list, since they are referenced by the list, they will never be recycled during the running of the program.
Java Weak reference to Java
- Java is the first mainstream language to use strong references as default object references. The previous (ANSI) C language only supported weak references. Then David Hostettler Wain and Scott Alexander Nesmith noticed that the event tree could not be released normally. As a result, in about 1998, they introduced strong and weak references that were counted and not counted respectively. If you create a weak reference and then use it to get the real object elsewhere in the code, because weak references cannot prevent garbage collection, get () may start to return `null` at any time (if the object is not strongly referenced).
import java.lang.ref.WeakReference; public class ReferenceTest {public static void main (String [] args) throws InterruptedException {WeakReference r = new WeakReference (new String ("I'm here")); WeakReference sr = new WeakReference ( "I'm here"); System.out.println ("before gc: r =" + r.get () + ", static =" + sr.get ()); System.gc (); Thread.sleep (100); // Only r.get () becomes null System.out.println ("after gc: r =" + r.get () + ", static =" + sr.get ());})
- Weak references can also be used to implement caching. For example, a weak hash table, that is, a hash table that caches various reference objects through weak references. When the garbage collector is running, if the application's memory footprint is too high, those cached objects that are no longer referenced by other objects will be automatically released. [1]