Android soft reference and weak reference details and example code

Android soft reference and weak reference

1. Softreference < T >: soft reference -- > when the memory of the virtual machine is insufficient, the object it points to will be recycled; When you need to get an object, you can call the get method.

2. WeakReference < T >: weak reference -- > may be recycled by the garbage collector at any time. You don't have to wait until the virtual machine is out of memory. When you want to get an object, you can also call the get method.

3. WeakReference is generally used to prevent memory leakage. To ensure that the memory is recycled by the virtual machine, softreference is mostly used to implement the cache mechanism (CACHE);

Instance softreference

If an object has only soft references, it is similar to a dispensable commodity. If the memory space is enough, the garbage collector will not recycle it. If the memory space is insufficient, it will recycle the memory of these objects. As long as the garbage collector does not recycle it, the object can be used by the program. Soft references can be used to implement memory sensitive caching.

For example, in the picture loading framework, weak references are used to implement memory caching.

Weak reference

Objects with only weak references have shorter lifecycles. When the garbage collector thread scans the memory area under its jurisdiction, once it finds an object with only weak references, it will reclaim its memory regardless of whether the current memory space is sufficient or not. However, since the garbage collector is a low priority thread, it is not necessary to quickly find objects with only weak references.

WeakReference<User> sr = new WeakReference<User>(new User());

Handler weak reference to prevent memory leakage

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>