Four reference types of in-depth learning objects in Android (strong reference, soft reference, weak reference, virtual reference)

Four reference types of in-depth learning objects in Android (strong reference, soft reference, weak reference, virtual reference)

[[429600]]

Preface

In Java, everything is considered an object, and references are used to manipulate objects. In JDK1.2, object references are divided into four levels, so that the program can control its life cycle more flexibly. The levels are as follows from high to low: strong > soft > weak > phantom reference. The GC garbage collector (Garbage Collection) has different processing methods for different types. Understanding these processing methods will help us write higher quality code.

Today we will learn:

1. Detailed explanation of citation

1. StrongReference

Strong references are the most commonly used references. If an object has a strong reference, the garbage collector will never recycle it. When memory space is insufficient, the Java virtual machine would rather throw an OutOfMemoryError error and cause the program to terminate abnormally than solve the problem of insufficient memory by arbitrarily recycling objects with strong references. For example, in the code String s="abc", the variable s is a strong reference to the string object "abc". As long as you assign a null value to the strong reference object s, the object can be recycled by the garbage collector; because the object no longer contains other strong references at this time;

  1. //str represents a strong reference, pointing to the new String() object
  2. String str = new String();

2. Weak references

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

  1. //Weak reference instance
  2. WeakReference weakReference = new WeakReference<>(context);
  3. //Get the reference saved by the weak reference
  4. Context ctx = weakReference.get();

3. Soft references

SoftReference: Soft reference –> When the virtual machine is out of memory, the object it points to will be recycled; when you need to get the object, you can call the get method;

Soft reference objects will not be reclaimed by the JVM quickly. The JVM will determine when to reclaim based on the current heap usage. It will only be reclaimed when the heap usage frequency approaches the threshold.

Basic Usage

  1. MySoftReference msf = new MySoftReference();
  2. SoftReference sf = new SoftReference(msf);
  3. MySoftReference mySoftReference =(MySoftReference) sf.get();

Basic Features

  • If there is enough memory, soft references will not be reclaimed by the JVM;
  • If there is not enough memory, references will be recycled based on the usage of the stack;
  • Unreclaimed soft references can always be owned by the program;
  • Soft references can be used in conjunction with reference queues (ReferenceQueue) to implement high-speed caches with tight memory;
  • If the object referenced by the soft reference is recycled, the Java virtual machine will add the soft reference object to the reference queue associated with it;
  1. ReferenceQueue rq = new ReferenceQueue();
  2. SoftReference sf = new SoftReference(msf,rf);

When the soft reference object is recycled, the ReferenceQueue queue stores the strongly referenced Reference, and then poll() can be used to determine whether there is an object in the current reference queue that has lost its soft reference. If the queue is empty, a null will be returned, otherwise the method returns the previous Reference object in the queue. You can detect which soft reference object is recycled and then clear it;

  1. Reference reference = null ;
  2. while((reference==(EmployeeRef)rq.poll())){
  3. //Clear operation
  4. reference = null ;
  5. System.gc();
  6. }

4. Phantom references

PhantomReference is the weakest reference. An object holding a phantom reference is almost the same as an object without a reference and may be garbage collected at any time. References obtained through the get() method of a phantom reference will fail (become null). Phantom references must be used together with the reference queue ReferenceQueue;

The ReferenceQueue reference queue is used to track the garbage collection process. When the garbage collector collects an object, if it finds that it still has a phantom reference, it will destroy the object after the collection and add the object pointed to by the phantom reference to the reference queue. The only way to determine whether a phantom reference is collected by GC is to determine whether it is added to the ReferenceQueue. This is also the only way to determine whether an object is recycled;

There is a finalize() method in the Java Object class. The principle is: once the garbage collector is ready to release the memory space occupied by the object, it will first call the finalize() method, and the memory occupied by the object will not be truly reclaimed until the next garbage collection action occurs. However, the problem is that the virtual machine cannot guarantee when finalize() will be called because the GC running time is not fixed;

This problem can be solved by using phantom references. Phantom references are mainly used to track garbage collection activities and are mainly used to achieve more sophisticated memory usage control, which is very meaningful for Android;

  1. //Reference queue
  2. ReferenceQueue queue = new ReferenceQueue<>();
  3. //Virtual reference
  4. PhantomReference phantomReference = new PhantomReference(new Object(), queue);
  5. Log.e(TAG, "Virtual reference: PhantomReference == " + phantomReference.get());
  6. //System garbage collection
  7. System.gc();
  8. System.runFinalization();

The reference obtained by phantomReference.get() is always null, calling the system to recycle garbage, queue.poll() obtains the saved reference object and removes it from this queue;

Phantom references cannot obtain the target reference through the get() method, and always return null. Source code:

  1. public T get() {
  2. return   null ;
  3. }

Summarize

  • Strong Reference: It will not be automatically recycled. It is the most difficult to be recycled by GC. It would rather throw an exception than recycle the object pointed to by the strong reference; in any scenario;
  • SoftReference: When memory is insufficient, GC will recycle the objects pointed to by soft references. They are rarely used and have been replaced by LruCache.
  • WeakReference: Regardless of whether the memory is sufficient or not, as long as the GC is executed, the object pointed to by the weak reference can be recycled; it is often used to avoid memory leaks;
  • Phantom Reference: It can be recycled at any time, also known as ghost reference, which is equivalent to not pointing to any instance reference; it tracks whether the object has been recycled and is rarely used.

This article is reproduced from the WeChat public account "Android Development Programming"

<<:  100 yuan per account! A gang used a face-changing app to "revive" tens of thousands of restricted WeChat accounts

>>:  When is the cheapest time to buy a mobile phone? Insiders say

Recommend

Can you buy near-expiry food at a 10% discount? Is it safe?

Have you ever bought expired food? When you go to...

Chery angrily denounces Mercedes-Benz's new energy trademark infringement

Chery Automobile previously launched a micro pure...

Why mobile phone screens tend to fail in winter

Why is the touch screen sometimes not very sensit...

What SEO strategies should startups adopt?

"The search rankings cannot rise as expected...

How did China's proud "yellow soil" come into being?

China has a long history and splendid civilizatio...

2019 Second Category E-commerce Promotion Insight Report!

The traditional e-commerce dividend has passed. I...

The underlying logical understanding of marketing planning!

Maybe we all have encountered this problem: Why d...

The childhood games of the 80s and 90s, which the 00s have never seen

Children are not divided into big or small, we ar...

What is the difference between server rental and server hosting?

As the Internet becomes more mature, the Internet...