编程知识 cdmana.com

There are four kinds of references in Java, including strong reference, soft reference, weak reference and virtual reference

Java Four types of references include strong references , Soft citation , Weak reference , Virtual reference .

 

Strong citation :

As long as the quotation exists , The garbage collector will never recycle
Object obj = new Object();
// Directly through obj Get the corresponding object Such as obj.equels(new Object());
And so obj Object to back new Object A strong reference of , Only when obj After this quote is released , The object will be released , This is also the form of coding we often use .


 

Soft citation :

It is not necessary to quote , Recycle before memory overflow , It can be realized by the following code
Object obj = new Object();
SoftReference<Object> sf = new SoftReference<Object>(obj);
obj = null;
sf.get();// Sometimes it returns null
Now sf It's right obj A soft reference , adopt sf.get() Method can get this object , Of course , When this object is marked as an object to be recycled , Then return to null;
The main user of soft reference implements the function similar to cache , In case of enough memory, the value is directly obtained by soft reference , No need to query data from busy real sources , Speed up ; When out of memory , Automatically delete this part of cached data , Look up the data from real sources .





 

Weak reference :

Recycle the second time you recycle , It can be realized by the following code
Object obj = new Object();
WeakReference<Object> wf = new WeakReference<Object>(obj);
obj = null;
wf.get();// Sometimes it returns null
wf.isEnQueued();// Returns whether the garbage is marked by the garbage collector as being collected
Weak references are recycled on the second garbage collection , Take the corresponding data through weak reference in a short time , You can get it. , When a second garbage collection is performed , Will return null.
Weak references are mainly used to monitor whether the object has been marked as garbage to be recycled by the garbage collector , Can be quoted by weak isEnQueued Method returns whether the object is marked by the garbage collector .






 

Virtual reference :

Recycle when recycling , Cannot get object value by reference , It can be realized by the following code
Object obj = new Object();
PhantomReference<Object> pf = new PhantomReference<Object>(obj);
obj=null;
pf.get();// Never return null
pf.isEnQueued();// Returns whether it has been deleted from memory
Virtual references are recycled every time they are recycled , By virtual reference get The data obtained by the method is null, So it's also called the ghost quote .
Virtual reference is mainly used to detect whether the object has been removed from memory .






 

Studying recently Java virtual machine , There's a problem with citation , Here is a summary of :

Original address :http://blog.csdn.net/coding_or_coded/article/details/6603549

The strength of objects 、 soft 、 Weak and virtual references
stay JDK 1.2 In previous versions , If an object is not referenced by any variable , Then the program can no longer use this object . in other words , Only objects are accessible (reachable) state , The program can use it . from JDK 1.2 Version start , Divide references to objects into 4 Class , So that the program can control the life cycle of the object more flexibly . this 4 The order of species level from high to low is : Strong citation 、 Soft citation 、 Weak quotation and virtual quotation .


 

⑴ Strong citation (StrongReference)
Strong references are the most commonly used references . If an object has a strong reference , That garbage collector will never recycle it . When memory runs out of space ,Java The virtual machine would rather throw OutOfMemoryError error , Causes the program to terminate abnormally , It will not solve the problem of insufficient memory by randomly recycling objects with strong references .  ps: Strong quotation is actually what we usually A a = new A() That's what it means .

⑵ Soft citation (SoftReference)
If an object has only soft references , Then 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 ( An example is given below ).
Soft references can be combined with a reference queue (ReferenceQueue) A combination of , If the object referenced by the soft reference is recycled by the garbage collector ,Java The virtual machine adds the soft reference to the reference queue associated with it .

⑶ Weak reference (WeakReference)
The difference between weak quotation and soft quotation is : Objects with only weak references have a shorter life cycle . In the process of the garbage collector thread scanning the memory area it governs , Once you find an object with only weak references , Whether the current memory space is enough or not , Will reclaim its memory . however , Because the garbage collector is a low priority thread , So it's not necessarily easy to find objects with only weak references .
Weak references can be associated with a reference queue (ReferenceQueue) A combination of , If the object referenced by the weak reference is garbage collected ,Java The virtual machine will add this weak reference to the reference queue associated with it .

⑷ Virtual reference (PhantomReference)
“ Virtual reference ” seeing the name of a thing one thinks of its function , It's the same thing , Different from other quotations , Virtual references do not determine the life cycle of an object . If an object only holds virtual references , Then it's the same as without any reference , It can be collected by the garbage collector at any time .
Virtual references are mainly used to track the activities of objects recycled by the garbage collector . One of the differences between virtual reference and soft reference and weak reference is : Virtual references must be with reference queues (ReferenceQueue) A combination of . When the garbage collector is ready to recycle an object , If it's found to have virtual references , Before reclaiming the object's memory , Add this virtual reference to and In the associated reference queue .












ReferenceQueue queue = new ReferenceQueue ();

PhantomReference pr = new PhantomReference (object, 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 .
Using soft references to build a cache of sensitive data
1 Why you need to use soft references

First , Let's look at an example of an employee information query system . We will use a Java Language implementation of employee information query system query stored in disk files or database Employee personnel file information in . As a user , It's quite possible that we need to go back and look at employee profiles that we looked at a few minutes or even seconds ago ( Again , We're browsing WEB When the page is often used “ back off ” Button ). In this case, we usually have two ways to implement the program : One is to store employee information that you have checked in the past in memory , Every one that stores employee file information Java The life cycle of an object runs through the entire application ; The other is when users start looking at other employees' profile information , Save the employee file information currently viewed Java Object end reference , So that the garbage collection thread can reclaim the memory space it occupies , When the user needs to browse the employee's profile information again , Reconstruct the employee's information . Obviously , A lot of memory will be wasted in the first method , The drawback of the second implementation is that even if the garbage collection thread has not yet garbage collected , The object containing the employee profile information is still intact in memory , An application needs to be rebuilt as well . We know , Accessing disk files 、 Access network resources 、 Query database and other operations are important factors that affect the execution performance of applications , If you can retrieve what hasn't been recycled Java References to objects , There will be fewer unnecessary visits , Greatly improve the running speed of the program .

2 If you use soft references
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 After object ,get() Method will return null.
Look at the code below :









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;

thereafter , This MyObject Objects become soft accessible objects . If the garbage collection thread does memory garbage collection , It's not because there's a SoftReference Reference to the object and always keep the object .Java Virtual machine's garbage collection thread on soft accessible objects and other general Java Objects are treated differently : Soft accessible objects are cleaned up by the garbage collection thread according to its specific Algorithm According to the requirement of memory . in other words , The garbage collection thread will throw OutOfMemoryError Before recycling soft accessible objects , Moreover, virtual opportunities should give priority to reclaiming soft accessible objects that have been idle for a long time , For those that have just been built or used “ new ” Soft object objects are retained by virtual machines as much as possible . Before recycling these objects , We can go through :
MyObject anotherRef=(MyObject)aSoftRef.get(); 
Regain a strong reference to the instance . And after recycling , call get() The method can only get null 了 .

3 Use ReferenceQueue Clean up lost soft reference objects SoftReference
As a Java object ,SoftReference In addition to the particularity of saving soft references , Also has the Java The generality of the object . therefore , When soft accessible objects are recycled , Although the SoftReference Object's get() Method returns null, But this SoftReference The object no longer has the value of being , An appropriate clearance mechanism is needed , Avoid large quantities SoftReference Memory leaks from objects . stay java.lang.ref The bag also provides ReferenceQueue. If you're creating SoftReference When the object , Used a ReferenceQueue Object as a parameter to SoftReference Construction method of , Such as :




ReferenceQueue queue = new
ReferenceQueue();

SoftReference
ref=new
SoftReference(aMyObject, queue); 
So when this SoftReference Soft quoted aMyOhject While being recycled by the garbage collector ,ref Strongly quoted SoftReference Objects are included in ReferenceQueue. in other words ,ReferenceQueue The objects saved in are Reference object , And it has lost its soft reference object Reference object . From the other ReferenceQueue The name can also be seen , It's a queue , When we call its poll() Method time , If this queue is not empty , Then it will return to the one in front of the queue Reference object .
At any time , We can all call ReferenceQueue Of poll() Method to check if any non strongly accessible objects it cares about are recycled . If the queue is empty , Will return a null, Otherwise, the method returns the previous one in the queue Reference object . Use this method , We can check which SoftReference The soft reference object has been recycled . So we can put these objects without soft references SoftReference Remove the object . The common way is :



SoftReference ref = null;

while ((ref = (EmployeeRef) q.poll()) != null) {

//  eliminate ref

}

版权声明
本文为[osc_ inj0cicw]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225090409060i.html

Scroll to Top