This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging

The level and intensity of the four references in Java from high to low are as follows: strong reference → soft reference → weak reference → virtual reference

When the garbage collector collects, some objects are collected and some are not. The garbage collector marks the living objects from the root Object Object, and then reclaims some unreachable objects and some referenced objects. As follows:

Reference types Time to be garbage collected use Time to live
Strong reference never The general state of the object Termination occurs when the JVM stops running
Soft references When memory is running out Object caching Terminating when out of memory
A weak reference Normal garbage collection Object caching Terminate after garbage collection
Phantom reference Normal garbage collection Trace the garbage collection of objects Terminate after garbage collection

1 StrongReference (StrongReference)

A strong reference is one of our most common objects. It is a non-recyclable resource, and the garbage collector (GC) will never reclaim it, even if the JVM is running out of memory and would rather throw an OutOfMemoryError and terminate the program than reclaim a strong reference object. If an object has a strong reference, the garbage collector will never reclaim it. As follows:

 Object strongReference = new Object();
Copy the code

When there is insufficient memory space, the Java Virtual Machine would rather throw an OutOfMemoryError, causing the program to terminate abnormally, than resolve the problem by arbitrarily recollecting objects with strong references. If the strong reference object is not used, it needs to be weakened so that GC can reclaim it, as follows:

 strongReference = null;
Copy the code

If you explicitly set a strongReference object to NULL or let it exceed the lifetime of the object, the GC considers that there is no reference to the object and can reclaim it. Exactly when to collect it depends on the GC algorithm.

public void test() { Object strongReference = new Object(); // Omit other operations}Copy the code

There is a strong reference inside a method that is held in the Java stack, while the actual reference (Object) is held in the Java heap. When the method finishes running, it exits the method stack, the reference object has zero references, and the object is reclaimed. But if the strongReference is a global variable, you need to set it to NULL when the object is not used, because strong references do not get garbage collected.

2 SoftReference

If an object has only soft references, then the garbage collector will not reclaim it if there is enough memory. If the memory space runs out, the memory of these objects is reclaimed. As long as the garbage collector does not reclaim it, the object can be used by the program. Soft references can be used to implement memory-sensitive caching.

// strongReference String strongReference = new String(" ABC "); // Soft reference String STR = new String(" ABC "); SoftReference<String> softReference = new SoftReference<String>(str);Copy the code

Soft references can be used in conjunction with a ReferenceQueue (ReferenceQueue). If the object referenced by the soft reference is garbage collected, the JAVA VIRTUAL Machine will add the soft reference to the reference queue associated with it.

 ReferenceQueue<String> referenceQueue = new ReferenceQueue<>();
 String str = new String("abc");
 SoftReference<String> softReference = new SoftReference<>(str, referenceQueue);
Copy the code

Note: Soft reference objects are only reclaimed when the JVM runs out of memory. We call the system.gc () method for notification only. When the JVM scans for reclaimed objects is determined by the JVM’s state. Even if a soft reference object is detected, it is not always reclaimed, only when there is insufficient memory.

The garbage collection thread reclaims soft reference objects before the VIRTUAL machine throws an OutOfMemoryError, and the virtual machine reclaims soft reference objects that have been unused for a long time as much as possible. “Newer” soft objects that have just been built or used are retained by the virtual machine as much as possible, which is why ReferenceQueue is introduced.

3. WeakReference

A weak reference object has a shorter life cycle than a soft reference object, and whenever GC finds that it has only weak references, it will reclaim it regardless of whether there is enough memory, but GC is a low priority thread, so it does not necessarily find objects that have only weak references very quickly.

The difference between a weak reference and a soft reference is that objects with only weak references have a shorter life cycle. When the garbage collector thread scans the area of memory it manages, if it finds an object with only weak references, it will reclaim its memory, regardless of whether the current memory space is sufficient. However, because the garbage collector is a low-priority thread, objects with only weak references are not necessarily quickly discovered.

 String str = new String("abc");
 WeakReference<String> weakReference = new WeakReference<>(str);
 str = null;
Copy the code

The JVM first sets the object reference in the soft reference to NULL and then notifies the garbage collector to collect:

 str = null;
 System.gc();
Copy the code

Note: You should remember an object with Weak Reference if it is used occasionally and you want it to be available whenever you use it, but you do not want to affect garbage collection.

The following code will make a weak reference a strong one again:

String str = new String("abc"); WeakReference<String> weakReference = new WeakReference<>(str); String strongReference = WeakReference.get (); // WeakReference.get ();Copy the code

Similarly, a weak reference can be used in conjunction with a ReferenceQueue (ReferenceQueue). If the object referenced by the weak reference is garbage collected, the Java virtual machine will add the weak reference to the ReferenceQueue associated with it.

4 PhantomReference

A dummy reference is, as the name suggests, a dummy. Unlike the other references, virtual references do not determine the life cycle of the object. If an object holds only virtual references, it is just as likely to be collected by the garbage collector at any time as if there were no references at all.

Application scenario:

Virtual references are primarily used to track the activity of an object being collected by the garbage collector. One difference between virtual references and soft and weak references is that:

Virtual references must be used in conjunction with the ReferenceQueue. When the garbage collector is ready to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object’s memory.

String str = new String("abc"); ReferenceQueue queue = new ReferenceQueue(); PhantomReference pr = new PhantomReference(STR, queue); PhantomReference pr = new PhantomReference(STR, queue);Copy the code

A program can determine whether a referenced object is about to be garbage collected by determining whether a virtual reference has been added to the reference queue. If a program finds that a virtual reference has been added to the reference queue, it can take the necessary action before the referenced object’s memory is reclaimed.