Four reference modes of Java

yu-Knight 2022-02-13 09:19:10 阅读数:832

reference modes java

java Memory management is divided into memory allocation and memory recovery , No programmer is responsible , The mechanism of garbage collection mainly depends on whether there is a reference to the object .

java References to objects include :
Strong citation , Soft citation , Weak reference , Virtual reference

Java There are two main purposes of providing these four reference types in :

The first is to let the programmer determine the life cycle of some objects by means of code ;

The second is in favor of JVM Garbage collection .


1. Strong citation

  It means creating an object and assigning it to a reference variable .

such as :

Object object =new Object();

String str ="hello";

  Strong references are never garbage collected when they have reference variables ,JVM Would rather throw OutOfMemory Errors also don't recycle such objects .

If you want to break the association between a strong reference and an object , You can explicitly assign references to null, In this way ,JVM The object will be recycled at the right time .

such as Vector Class clear Method by assigning the reference to null To achieve the cleaning work :

2. Soft citation (SoftReference)

If an object has a soft reference , Enough memory space , The garbage collector won't recycle it ;

If there's not enough memory , It will reclaim the memory of these objects . As long as the garbage collector doesn't recycle it , This object can be used by the program .

Soft references can be used to implement memory sensitive caching , For example, Web caching 、 Image cache, etc . Using soft references can prevent memory leaks , Enhance the robustness of the program .   
SoftReference The feature is that one instance of it is saved to one Java Soft references to objects , The existence of the soft reference does not prevent the garbage collection thread from Java Recycling of objects . in other words , once SoftReference Saved a pair of Java After soft reference of object , In the garbage thread on This Java Before the object is recycled ,SoftReference Class get() Method returns Java A strong reference to an object .

in addition , Once the garbage thread recycles the Java Object after ,get() Method will return null.

MyObject aRef = new  MyObject();  

SoftReference aSoftRef=new SoftReference(aRef);  

here , For this MyObject object , There are two reference paths , One is from SoftReference Soft references to objects , One comes from a variable aReference A strong reference to , So this MyObject Objects are strongly accessible objects .

immediately , We can end aReference For this MyObject Strong references to instances :

aRef = null; 


3. Weak reference (WeakReference)

Weak references are also used to describe nonessential objects , When JVM When recycling , Whether the memory is sufficient or not , All objects associated with weak references will be recycled . stay java in , use java.lang.ref.WeakReference Class .

Weak references are simply the ability to keep objects in memory. References that are not so strong . Use WeakReference, The garbage collector will help you decide when to recycle the referenced object and remove the object from memory . Create a weak reference as follows

WeakReference<Widget> weakWidget = new WeakReference<Widget>(widget);
Use weakWidget.get() You can get the real Widget object , Because weak references cannot prevent the garbage collector from collecting them ( The weakly referenced object is bound to be in the next GC Is recycled ), You'll find that ( When there is no strong reference to widget Object time ) Use get Suddenly return when null.

Solve the problem of... In the above strong reference strongRef The problem of serial number recording , The easiest way is to use Java Built in WeakHashMap class .WeakHashMap and HashMap Almost the same as , The only difference is its key ( It's not worth it !!!) Use WeakReference quote . When WeakHashMap When the key is marked as garbage , The entry corresponding to this key will be automatically removed . This avoids the unnecessary above strongRef The problem of manually deleting objects . Use WeakHashMap It can be easily converted to HashMap perhaps Map.


4. Virtual reference (PhantomReference)

Virtual references and previous soft references 、 Weak quotes are different , It doesn't affect the life cycle of the object . stay java of use java.lang.ref.PhantomReference Class represents . If an object is associated with a virtual reference , It's the same as not quoting , It can be collected by the garbage collector at any time .

It should be noted that , Virtual references must be associated with reference queues , When the garbage collector is ready to recycle an object , If it's found to have virtual references , Will add this virtual reference to it In the associated reference queue . The program can judge whether a virtual reference has been added to the reference queue , To see if the referenced object is going to be garbage collected . If the program finds that a virtual reference has been added to the reference queue , Then you can take the necessary action before the memory of the referenced object is recycled .

Virtual reference usage scenarios are mainly composed of two . It allows you to know exactly when the object it references is removed from memory . This is especially true when dealing with large files like pictures . When you decide that a picture data object should be recycled , You can use the virtual reference to judge whether the object is recycled and then continue to load the next image . This can avoid memory overflow errors as much as possible .


Soft quotes and weak quotes
    For strong quotes , We usually use it when we write code . And for the other three types of references , The most commonly used are soft references and weak references , this 2 Species have similarities and differences . They are used to describe non essential objects , But objects associated with soft references are recycled only when memory is low , The objects associated with weak references are in JVM It's always recycled when it comes to garbage collection .

How to use soft reference and weak reference to solve OOM problem

I talked about the basic knowledge of soft reference and weak reference , So how to use them to optimize program performance , To avoid OOM The question of ?

Here's an example , If there is an application that needs to read a large number of local images , If every time you read a picture, read it from the hard disk , It will seriously affect the performance , But if it's all loaded into memory , It may cause memory overflow , Using soft references can solve this problem .

The design idea is : Use one HashMap To save the image path and Mapping between soft references associated with corresponding image objects , When there is not enough memory ,JVM Automatically reclaims the space occupied by these cached image objects , So as to effectively avoid OOM The problem of . stay Android In the development of a large number of pictures download will often use .

See... For other details :Java Four ways of reference

copyright:author[yu-Knight],Please bring the original link to reprint, thank you.