Four reference types in Java

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());
In this way, the obj object has a strong reference to the following new Object. Only when the obj reference is released, the object will be released, which is also the coding form we often use.

 

Soft references:

Non-essential references, recycling before memory overflow, can be achieved by the following code
Object obj = new Object();
SoftReference<Object> sf = new SoftReference<Object>(obj);
obj = null;
sf.get();//Sometimes it returns null
At this time, sf is a soft reference to obj, and the object 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;
The main user of soft reference implements a function similar to cache. When the memory is sufficient, the value is directly obtained through the soft reference, without querying data from the busy real source, which improves the speed; when the memory is insufficient, this part of the cached data is automatically deleted. source to query these data.

 

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 the garbage collector is marked as about to be recycled
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.

 Lead to: https://www.cnblogs.com/yw-ah/p/5830458.html

Guess you like

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