1, Why are there four kinds of references
01
At the beginning, when an object is not referenced (that is, there is no attribute / variable reference, for example, Object ob=new Object();ob=null;) It will be automatically recycled by the JVM. It is a strong reference before it is equal to null. For example, if you go to a restaurant for dinner, you stand in a position that refers to this position. The waiter (JVM) will not come and take away your tableware. When you leave, the waiter will take away your tableware
02
With the development of Java, the requirements are becoming more and more diversified. Some people hope that when an object is not referenced, it will not be taken away, but stored in memory for a period of time, so soft reference was born. Then, in the above example, the owner of the restaurant (Java Developer) thought, ah, this is not good. As soon as the guest walked away, he took away the tableware of others, which not only made the guest eat less and less, but also made the guest less and less want to eat here. So he gave the guest a sign that said "someone eats", so that the waiter would not eat when the guest walked away, He took the tableware away
03
Others just want to use an object in a short time, and don't want to manage when to cancel the reference and let the JVM clean it up automatically. Therefore, weak references appear. Weak references are opposite to strong references. Strong refers to having absolute control over the object, while weak refers to not wanting to control the object and leaving it all to the JVM. Although the boss didn't know the rules of putting another sign on the dining room after ten minutes, he didn't think it was OK to put another sign on the dining room. However, if the boss didn't know what sign to put on the dining room, he could avoid it, The waiter will take away the tableware
04
There are also some people who want to judge whether the object has been cleaned up by the JVM on the basis of weak reference or soft reference, so the virtual reference comes out. The virtual reference is not provided to the JVM, but to the developers to facilitate the developers to check whether the object has been cleaned up. For example, the boss received many complaints that I have to come back for dinner, but the tableware was taken away, The boss thought, there is a problem. We have to find a way. So I decided to equip each position with a communicator. When the waiter wants to collect the tableware, he will tell the guest through the communicator
2, Four references
The above is just a brief introduction to the four references. Next, we will introduce these four references in more detail in combination with the code
Strong reference
Strong reference means that when an object is referenced by an attribute / field, the JVM will not recycle the object. When the memory space is insufficient, the JVM would rather throw outofmoryerror (memory overflow error) than recycle the object. Strong reference is the most common reference, which is generally used when the object cannot be deleted at will
public static void main(String[] args) throws Exception{ System.out.println("start"); Object object=new Object(); System.gc();System.out.println(object); object=null; System.gc(); System.out.println(object); System.out.println("end"); } //output //startjava.lang.Object@14ae5a5nullend Copy code
Soft reference
Soft reference refers to the association of an object. You can find the object through this association. The JVM will recycle the object only when the memory is insufficient. The soft reference needs JAVA Lang.ref.softreference class. Generally, it is used for useful but not necessary or short-term objects, such as cache. Storing data in memory can speed up the corresponding speed. When the memory is insufficient, deleting the cache will not have an impact
public static void main(String[] args) throws Exception{ System.out.println("start"); Object object=new Object(); System.gc();Thread.sleep(500); SoftReference softReference=new SoftReference(object); System.out.println(softReference.get()); System.gc();Thread.sleep(500); System.out.println(softReference.get()); System.out.println("end"); } result start java.lang.Object@14ae5a5 java.lang.Object@14ae5a5 end Copy code
Weak reference
A weak reference is also associated with an object. However, when the JVM performs periodic gc or the memory is insufficient, the object will be recycled, regardless of whether the memory is enough. A weak reference needs to use Java Lang.ref.weakreference class. Generally, it is used for those unimportant objects or objects that are currently used only once. For example, the judgment condition in if. If you want to judge only once, you can use weak reference
public static void main(String[] args) throws Exception{ System.out.println("start"); Object object=new Object(); System.gc();Thread.sleep(500); WeakReference weakReference=new WeakReference(new Object()); System.out.println(weakReference.get()); System.gc();Thread.sleep(500); System.out.println(weakReference.get()); System.out.println("end"); } result start java.lang.Object@14ae5a5 null end Copy code
Virtual reference
Virtual reference is a fictitious reference, which will not affect the life cycle of the object. It is just a tool to detect whether the object exists. Virtual reference needs to be implemented by ReferenceQueue class and phantom reference class
public static void main(String[] args) throws Exception{ System.out.println("start"); Object object=new Object(); ReferenceQueue q=new ReferenceQueue(); PhantomReference<Object> phantomReference=new PhantomReference<Object>(object,q); System.gc(); Thread.sleep(500); //The get() method always returns null System.out.println(phantomReference.isEnqueued()); object=null; System.gc(); Thread.sleep(500); System.out.println(phantomReference.isEnqueued()); System.out.println("end"); } result start false true end Copy code
last
The four kinds of references are finished. In the future, when programming, you can consider adding the following three kinds of references to the code to improve the control of the object life cycle. Make a summary. Strong references. The JVM dare not arbitrarily clear weak references. Soft references corresponding to strong references. When objects are recycled, you can't determine whether virtual references exist or not
Author: programmer Xu Xiaobai
Link: https://juejin.cn/post/6972341431859937310
Source: Nuggets
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.