Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money

preface

In Java, everything is treated as an object, and references are used to manipulate objects;

In JDK1.2, object references are divided into four levels, so that programs can control their life cycle more flexibly. The level is from high to low: strong > soft > weak > virtual;

The Garbage Collection does different things for different types, and knowing how to do these things helps us write higher-quality code;

Today we are going to learn

One, detailed explanation of citation

1. Strongly reference StrongReference

Strong references are the most commonly used references. If an object has a strong reference, the garbage collector will never collect it. 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. For example, the variable s in String s= “ABC” is a strong reference to the String object “ABC”. If you assign a null value to a strongly referenced object S, it can be collected by the garbage collector. Because the object now has no other strong references;

// STR is a strong reference, pointing to the object new String().Copy the code

2. Weak references

A WeakReference is a reference type that is weaker than a soft reference, which is similar to a soft reference. The difference is that a WeakReference cannot prevent garbage collection. When the garbage collection mechanism is running, if an object reference is a WeakReference, the object will be collected regardless of whether the memory space is enough. Weak references are often used to prevent memory leaks, most commonly caused by singletons and handlers;

// WeakReference WeakReference = new WeakReference<>(context); Context CTX = weakReference.get(); Context CTX = weakReference.get();Copy the code

3. Soft references

SoftReference: SoftReference – > if the vm memory is insufficient, the object to which the vm refers is reclaimed. To get an object, call the get method;

Soft reference objects are not quickly recycled by the JVM, which determines when to recycle based on the current heap usage and only when the heap usage is close to the threshold.

Basic usage

  MySoftReference msf = new MySoftReference();    SoftReference sf = new SoftReference(msf);    MySoftReference mySoftReference =(MySoftReference) sf.get();
Copy the code

The basic characteristics of

  • If there is enough memory, soft references are not reclaimed by the JVM;

  • If memory is low, references are recycled based on stack usage;

  • Soft references that are not reclaimed are always available to the program;

  • Soft references can be used in conjunction with reference queues (ReferenceQueue) to implement memory constrained caching;

  • If the object referenced by a soft reference is reclaimed, the Java virtual machine adds the modified soft reference object to its associated reference queue.

    ReferenceQueue rq = new ReferenceQueue(); SoftReference sf = new SoftReference(msf,rf);

When the soft Reference object is recovered, the Reference of strong Reference is stored in the ReferenceQueue queue, and then the poll() can be used to determine whether the current Reference queue has lost soft Reference objects. If the queue is empty, Returns a NULL, otherwise the method returns the previous Reference object in the queue. You can detect which soft reference object is being reclaimed and then clean it up;

Reference reference =null; While ((reference==(EmployeeRef)rq.poll())){// Delete operation reference= null; System.gc(); }Copy the code

4. Virtual references

A PhantomReference is the weakest reference, and an object holding a PhantomReference is almost the same as an object without a reference and can be collected by the garbage collector at any time. All references retrieved through the get() method of the virtual reference fail (null). The virtual reference must be used with the ReferenceQueue of the ReferenceQueue;

The ReferenceQueue ReferenceQueue is used to track the garbage collection process. When the garbage collector collects an object and finds that it has a virtual reference, it destroys the object after collection and adds the object to the reference queue. The only way to determine whether a virtual reference is recycled is by whether it is added to the ReferenceQueue.

Java Object class has finalize() method, principle: Once the garbage collector is ready to free the memory space occupied by objects, the Finalize () method will be called first, and the next garbage collection will happen, but the problem is that the VIRTUAL machine cannot guarantee when Finalize () will be called, because the GC running time is not fixed.

Virtual references solve this problem. Virtual references are used to track garbage collection activities. Virtual references are mainly used for fine-grained memory usage control, which makes sense for Android.

ReferenceQueue queue = new ReferenceQueue<>(); // PhantomReference PhantomReference = new PhantomReference(new Object(), queue); Log.e(TAG, "PhantomReference ==" + phantomreference.get ()); // System garbage collection system.gc (); System.runFinalization();Copy the code

Phantomreference.get () retrieves null references and calls the system to collect garbage. Queue.poll () retrieves the saved reference object and removes it from the queue.

A virtual reference cannot get a reference to a target using the get() method.

    public T get() {        return null;    }
Copy the code

conclusion

  • A StrongReference is one of the most difficult objects to be reclaimed by the GC. An exception is thrown rather than the object to which a StrongReference is referred. Any scene;

  • SoftReference: when the memory is insufficient, the GC collects a SoftReference object that is seldom used and is replaced by LruCache.

  • WeakReference: regardless of insufficient memory, as long as GC can recover the object pointed to by WeakReference; Often used to avoid memory leaks;

  • PhantomReference: can be collected at any time, also known as a ghost reference, equivalent to no reference to any instance; Tracking whether objects are recycled, rarely used;

Say goodbye to shape, tripartite library, ShapeableImageView usage details

Good recommendation

Android Advanced: Fully embrace the Activity Results API instead of onActivityResult

Android source code advanced in-depth understanding of SharedPreference principle mechanism

Study should “combine work and rest”

Android advanced desktop tasks and scheduling services and abandoned AlarmManager to fully embrace WorkManager

Android transition animation depth analysis

Java advanced in-depth understanding of load balancing algorithm implementation principle of 5

Advanced Coil for Android – Full explanation of kotlin’s photo gallery

History recommendation, mutual encouragement

Android advanced view coordinate system comprehensive detailed solution

Happy National Day: learning progress together

Good recommendation

Java thread concurrency AQS principle mechanism comprehensive detailed explanation