1. StrongReference

Strong references are the most commonly used references. If an object has a strong reference, the garbage collector will never collect it. As follows:

Object o=new Object(); / / strong referenceCopy the code

When running out of memory, the Java virtual machine would rather throw outofMemoryErrors to abort the program than randomly recycle objects with strong references to resolve the memory problem. If not, use the following method to weaken the reference:

o=null; // Help the garbage collector collect this objectCopy the code

Explicitly setting O to NULL, or beyond the life of the object, the GC considers that there is no reference to the object, and the object can be reclaimed. Exactly when to collect depends on the GC algorithm.

For example:

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

Inside a method there is a strong reference, which is stored in the stack, and the actual reference content (Object) is stored in the heap. When the method is finished, it exits the stack, the reference to the content does not exist, and the Object is reclaimed. However, if the o is a global variable, it needs to be null when the object is not used, because strong references are not garbage collected.

Strong references are very important in practice, for example, ArrayList implementation source code:

private transient Object[] elementData;
public void clear() {
        modCount++;
        // Let gc do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
}
Copy the code

A private array of variables elementData is defined in the ArrayList class, and when the method is called to empty the array, you can see the assignment of null to the contents of each array. Unlike elementData=null, strong references still exist, avoiding reallocation of memory in subsequent calls to methods such as add() to add elements. Using methods such as clear() to free memory is particularly useful for reference types held in arrays, so that memory can be freed in time.

2. SoftReference

If an object has only soft references, there is enough memory for the garbage collector not to reclaim it; If you run out of memory, the objects are reclaimed. As long as the garbage collector does not collect it, the object can be used by the program. Soft references can be used to implement memory sensitive caching.

String str=new String("abc"); // Strongly reference SoftReference<String> softRef=new SoftReference<String>(STR); / / soft referencesCopy the code

When memory is insufficient, it is equivalent to:

If(JVM. Memory out ()) {STR = null; // Convert to a soft reference system.gc (); // Garbage collector to collect}Copy the code

Soft references have important practical applications, such as the browser back button. When you press Back, is the content of the page displayed on the back page rerequested or retrieved from the cache? It depends on the implementation strategy.

(1) If a web page is recycled at the end of browsing, then click back to view the previous browsing page, need to rebuild

(2) If the browsing web pages are stored in memory, it will cause a large amount of memory waste, and even cause memory overflow

This is where soft references can be used

Browser prev = new Browser(); SoftReference sr = new SoftReference(prev); If (sr.get()! =null){ rev = (Browser) sr.get(); }else{prev = new Browser(); // Sr = new SoftReference(prev) is reclaimed because of insufficient memory. // rebuild}Copy the code

This is a good solution to the actual problem. A soft reference can be used in conjunction with a ReferenceQueue (ReferenceQueue), and if the object referenced by the soft reference is collected by the garbage collector, the Java virtual machine adds the soft reference to the ReferenceQueue associated with it.

3. WeakReference

The difference between weak and soft references is that objects with only weak references have a shorter lifetime. When the garbage collector thread scans the memory area under its control, once it finds an object with only weak references, it reclaims its memory regardless of whether the current memory space is sufficient. However, because the garbage collector is a low-priority thread, objects that have only weak references are not necessarily found quickly.

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

When the garbage collector does a scan collection, it is equivalent to:

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

If the object is used sporadically and you want it to be available whenever you use it, but you don’t want to affect the garbage collection of the object, then you should use Weak Reference to remember the object.

The following code makes STR a strong reference again:

String  abc = abcWeakRef.get();
Copy the code

Weak references can be used in conjunction with a ReferenceQueue (ReferenceQueue), and if the object referenced by a weak reference is garbage collected, the Java virtual machine adds the weak reference to the ReferenceQueue associated with it.

When you want to reference an object, but the object has its own life cycle, and you don’t want to interfere with the life cycle of the object, you are using weak references. This reference does not have any additional impact on the garbage collection judgment of the object

public class ReferenceTest { private static ReferenceQueue<VeryBig> rq = new ReferenceQueue<VeryBig>(); public static void checkQueue() { Reference<? extends VeryBig> ref = null; while ((ref = rq.poll()) ! = null) { if (ref ! = null) { System.out.println("In queue: " + ((VeryBigWeakReference) (ref)).id); } } } public static void main(String args[]) { int size = 3; LinkedList<WeakReference<VeryBig>> weakList = new LinkedList<WeakReference<VeryBig>>(); for (int i = 0; i < size; i++) { weakList.add(new VeryBigWeakReference(new VeryBig("Weak " + i), rq)); System.out.println("Just created weak: " + weakList.getLast()); } System.gc(); Thread.currentthread ().sleep(6000); } catch (InterruptedException e) { e.printStackTrace(); } checkQueue(); } } class VeryBig { public String id; Byte [] b = new byte[2 * 1024]; public VeryBig(String id) { this.id = id; } protected void finalize() { System.out.println("Finalizing VeryBig " + id); } } class VeryBigWeakReference extends WeakReference<VeryBig> { public String id; public VeryBigWeakReference(VeryBig big, ReferenceQueue<VeryBig> rq) { super(big, rq); this.id = big.id; } protected void finalize() { System.out.println("Finalizing VeryBigWeakReference " + id); }}Copy the code

The final output is:

Just created weak: com.javabase.reference.VeryBigWeakReference@1641c0
Just created weak: com.javabase.reference.VeryBigWeakReference@136ab79
Just created weak: com.javabase.reference.VeryBigWeakReference@33c1aa
Finalizing VeryBig Weak 2
Finalizing VeryBig Weak 1
Finalizing VeryBig Weak 0
In queue: Weak 1
In queue: Weak 2
In queue: Weak 0
Copy the code

4. Virtual Reference

Unlike the other references, virtual references do not determine the life cycle of an object. If an object holds only virtual references, it can be collected by the garbage collector at any time, just as if there were no references at all.

Virtual references are mainly used to track the activity of objects being collected by the garbage collector. One difference between a virtual reference and a soft or weak reference is that a virtual reference must be used in conjunction with a ReferenceQueue. When the garbage collector is about to reclaim an object and finds that it has a virtual reference, it adds the virtual reference to the reference queue associated with it before reclaiming the object’s memory.

5, summary

The levels of Java4 class references are, in descending order:

Strong > Soft > Weak > Virtual

Here’s a look at the differences in garbage collection:

When the garbage collector collects, some objects are collected and some are not. The garbage collector marks alive objects from the root Object and then reclaims unreachable objects and references. For those who are not familiar with this, see the following article:

To illustrate this, use the following table:

Reference: 1, 2, http://blog.csdn.net/lifetragedy?viewmode=contents, http://www.cnblogs.com/skywang12345/p/3154474.htmlCopy the code