Java four kinds of references include strong reference, soft reference, weak reference, virtual reference

Java four kinds of references include strong reference, soft reference, weak reference, virtual reference

Strong citation:

As long as the reference exists, the garbage collector will never collect

Object obj = new Object();

The corresponding object can be obtained directly through obj, such as obj.equels(new Object());
and such a strong reference of the obj object to the following new Object , the object will be released only after the reference of obj is released , which is also A form of encoding that we often use.

 

Soft references:

It is not necessary to refer to, and recycle before the memory overflows , which can be achieved by the following code:

Object obj = new Object();
SoftReference<Object> sf = new SoftReference<Object>(obj);
obj = null;
sf. get() ; ( Get this object through get, because obj points to null, the obj object will be recycled when it is recycled, but if it has not been recycled, you can get this object, if it has been recycled, it will return null)

At this time, sf is a soft reference to the obj object , which can be obtained through the sf.get() method . Of course, when the object is marked as an object that needs to be recycled, it returns null;
soft references are mainly used to achieve similar The function of caching , in the case of sufficient memory, directly obtains values ​​through soft references, without querying data from a busy real source, improving the speed;

When memory is low, this part of the cached data is automatically deleted, and the data is queried from the real source.

 

Weak reference:

Recycling during the second garbage collection can be achieved 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 it is marked by the garbage collector for garbage to be collected

Weak references are collected during the second garbage collection. The corresponding data can be retrieved through weak references in a short period of time. When the second garbage collection is performed, null will be returned.
Weak reference is mainly used to monitor whether the object has been marked as garbage to be collected by the garbage collector. The isEnQueued method of weak reference can return whether the object is marked by the garbage collector.

Dummy reference:

Recycling during garbage collection, the object value cannot be obtained by reference, which can be achieved by the following code

Object obj = new Object();
PhantomReference<Object> pf = new PhantomReference<Object>(obj);
obj=null;
pf.get(); // Always return null 
pf.isEnQueued(); // Return whether it has been deleted from memory

The virtual reference is recycled every time it is garbage collected. The data obtained by the get method of the virtual reference is always null , so it is also called a ghost reference .
Phantom references are mainly used to detect whether an object has been deleted from memory .

 

Strong, soft, weak and phantom references
to objects In versions prior to JDK 1.2, if an object was not referenced by any variable, the program could no longer use the object. That is, the program can only use the object if it is in the reachable state. Since JDK 1.2 version, the reference of objects is divided into four levels, so that the program can control the life cycle of the object more flexibly. The 4 levels from high to low are: strong reference, soft reference, weak reference and virtual reference.

⑴ Strong reference (StrongReference)
Strong reference is the most commonly used reference. If an object has a strong reference, the garbage collector will never collect it . When the memory space is insufficient, the Java virtual machine would rather throw an OutOfMemoryError error to cause the program to terminate abnormally, rather than solve the problem of insufficient memory by arbitrarily reclaiming objects with strong references. ps: Strong reference is actually what we usually mean by A a = new A().

(2) Soft Reference (SoftReference)
If an object has only soft references, the memory space is sufficient, and the garbage collector will not reclaim it; if the memory space is insufficient, the memory of these objects will be reclaimed . The object can be used by the program as long as it is not collected by the garbage collector. Soft references can be used to implement memory-sensitive caches (examples are given below).
Soft references can be used in conjunction with a reference queue (ReferenceQueue). If the object referenced by the soft reference is reclaimed by the garbage collector, the Java virtual machine will add the soft reference to the associated reference queue .

(3) Weak reference (WeakReference)
The difference between a weak reference and a soft reference is that an object with only a weak reference has a shorter life cycle . In the process of scanning the memory area under the jurisdiction of the garbage collector thread , once an object with only weak references is found, its memory will be reclaimed regardless of whether the current memory space is sufficient or not . However, since the garbage collector is a very low-priority thread, objects that only have weak references will not necessarily be discovered quickly .
Weak references can be used in conjunction with a reference queue (ReferenceQueue),If the object referenced by the weak reference is garbage collected, the Java virtual machine adds the weak reference to the reference queue associated with it .

⑷ Phantom Reference (PhantomReference)
"Phantom Reference", as the name suggests, is just in name only . Unlike other references, Phantom Reference does not determine the life cycle of an object. If an object only holds phantom references, then it can be collected by the garbage collector at any time as if it had no references at all .
Phantom references are primarily used to track the activity of objects being reclaimed by the garbage collector . One difference between virtual references and soft references and weak references is that virtual references must be used in conjunction with reference queues . When the garbage collector is ready to reclaim an object, if it finds that it still has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the memory of the object .

ReferenceQueue queue = new ReferenceQueue ();

PhantomReference pr = new PhantomReference (object, queue); 

The program can know whether the referenced object is about to be garbage collected by judging whether a virtual reference has been added to the reference queue. If the program finds that a virtual reference has been added to the reference queue,

Then the necessary action can be taken before the memory of the referenced object is reclaimed .

 

Building a cache of sensitive data using soft references

1 Why do you need to use soft references

First, let's look at an example of an employee information query system. We will use an employee information query system implemented in Java language to query employee personnel file information stored in a disk file or database . As a user, it is entirely possible that we need to go back and view employee file information that we viewed minutes or even seconds ago, similar to browsing a web page, but the data does not require a refresh (similarly, when we browse web pages, we often use "" Back" button ).

At this time, we usually have two program implementation methods:

One is to save the employee information viewed in the past in memory, and the life cycle of each Java object that stores employee profile information runs through the entire application.

The other is that when the user starts to view the profile information of other employees, the reference to the Java object that stores the currently viewed employee profile information is ended , so that the garbage collection thread can reclaim the memory space occupied by it, and when the user needs to browse again When the employee's profile information, rebuild the employee's information .

Obviously, the first implementation method will cause a lot of memory waste, and the second implementation has the disadvantage that even if the garbage collection thread has not been garbage collected, the object containing the employee file information is still well preserved in the memory, and the application is also To rebuild an object . We know that operations such as accessing disk files, accessing network resources, and querying databases are all important factors that affect the execution performance of applications. If we can re-acquire the references of those Java objects that have not been recycled, unnecessary access will be reduced and greatly improved. The speed at which the program runs .

2 If using soft references

The characteristic of SoftReference is that an instance of it holds a soft reference to a Java object , and the existence of the soft reference does not prevent the garbage collection thread from recycling the Java object . That is to say, once SoftReference saves a soft reference to a Java object, before the garbage thread recycles the Java object , the get() method provided by the SoftReference class returns a strong reference to the Java object . Also, the get() method will return null once the Java object is reclaimed by the garbage thread .

MyObject aRef = new
MyObject();
SoftReference aSoftRef = new SoftReference (aRef);

At this point, for this MyObject object, there are two reference paths , one is a soft reference from the SoftReference object, and the other is a strong reference from the variable aReference , so this MyObject object is a strongly accessible object.
Immediately, we can end aReference's strong reference to this MyObject instance :

aRef = null;

Thereafter, the MyObject object becomes a soft reachable object . If the garbage collection thread performs memory garbage collection, the object will not always be retained because there is a SoftReference to the object .

The garbage collection thread of the Java virtual machine treats soft-reachable objects differently from other general Java objects: the cleanup of soft -reachable objects is determined by the garbage collection thread according to its specific algorithm according to memory requirements . That is to say, the garbage collection thread will reclaim soft reachable objects before the virtual machine throws OutOfMemoryError , and the virtual machine will give priority to reclaiming soft reachable objects that have been idle for a long time as much as possible. "Soft reversible objects are preserved as much as possible by the virtual machine . Before recycling these objects,

We can pass:

MyObject anotherRef=(MyObject)aSoftRef.get();

Regain a strong reference to the instance . After recycling, calling the get() method can only get null.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325205596&siteId=291194637