Java controls the reference type of classes and makes rational use of memory

Java provides Java Lang.ref package. The classes under this package are related to the garbage collection mechanism

First, introduce the centralized reference types of Java objects

1. Strong reference

Strong reference is the most common. Creating an object is a strong reference, such as string a = new string ("1");

No matter whether the system memory is tight or not, as long as the object still has strong references, it will not be recycled by the garbage collection mechanism

2. Soft reference

When the system memory is sufficient, it will not be recycled. When the system memory is insufficient, it will be recycled

3. Weak reference

When the garbage collection mechanism is running, it is always recycled

4. Virtual reference

Track the status of objects being garbage collected

Check whether the reference queue associated with the virtual reference already contains the specified virtual reference, so as to know whether the object referenced by the virtual reference is about to be recycled

Then introduce reference related classes

2. WeakReference: weak reference type, for example:

3. Weakhashmap: map of weak reference type. This class is Java Util package

When the garbage collection mechanism runs, all key value pairs will be cleared unless some keys have strong references to them

4. Phantom reference: virtual reference type, similar to no reference. It should be used in combination with reference queue

I don't think it's very useful, so I won't give an example. If you're interested, check it yourself

5. ReferenceQueue: reference queue, which is used to save references of recycled objects

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>