Java reference types you must know [Conclusion]

Summary of four reference types

Reference level: strong reference > soft reference > weak reference > virtual reference

understand

As mentioned at the beginning, the four reference types are set to better control the life cycle of the object and allow the code to interfere with the GC process to a certain extent. Therefore, the reference types are mainly related to garbage collection.

For JVM, GC and memory, it can be understood that memory is like your drawer. This drawer has a certain size and can't store things indefinitely.

The JVM is like yourself, sorting out drawers from time to time. The objects of application are like things in a drawer, the necessities of life are like strong references, and the things that may be used (non necessities) are like soft references or weak references.

When the drawer is still empty, you don't care about putting some non essential goods, but with more and more things to buy, when the drawer can't fit, you need to choose some things according to the importance and throw them out of the drawer. This process is like GC.

When the JVM has enough memory, it will not recycle soft referenced objects, but when the memory is tight, it will clean them up.

Comparison of four reference types

Digression

emmmm…. I always think something is missing. Have you ever thought about why there is no strongreference class?

Well, be reasonable. Soft references, weak references and virtual references all have their corresponding classes. Why do strong references not? Imagine that if there is a strongreference class, it will be more convenient to judge the reference type in the custom cache. In fact, in guava's localcache, a strongvaluereference class is indeed constructed to wrap a strong reference.

So when you want to build your own cache wheel, you can first see if someone else's wheel works.

So far, this series has come to an end. In order to write this series of articles, I spent a lot of thought. It feels like cave exploration that is getting closer and closer to the bottom. The winding path of this exploration process is secluded, and the bright place is actually the best reward.

For learning, it is like the process of opening up the meridians. From scattered points to slowly connecting them into lines, the connection between points will give people great pleasure. Finally, if these points can be woven into a network, it will be like opening up the eight meridians of the strange meridians. Knowledge is just captured by hand.

(this B is installed well, and there are some more details in it. Ha ha, ha ha, slip away)

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
分享
二维码
< <上一篇
下一篇>>