One of the java reference types you must know — strong reference

definition

explain

Don't be frightened by this strong word and think that this reference is very powerful. In fact, strong reference is the general reference type used in the program. Take a simple Chestnut:

String s = new String("Hello Frank!");

If you are not clear about accessibility, you can read this article.

When you declare a variable and point to an instance, you are actually creating a strong reference. So, since it is called strong reference, where is it "strong"?

This is mainly reflected in that when the JVM performs GC, as long as the object has a strong reference associated with it, it will never be recycled. Even if the memory is insufficient, the object pointed to by the strong reference will not be recycled.

If you don't need to use an object, you can set the corresponding reference to null and eliminate strong references to help the garbage collector recycle. Because too many strong references are also the culprit of oom.

s = null;

If you explicitly set dereference, or it is beyond the life cycle of the object, the JVM will think that there is no reference to the object, and the object may be recycled. However, the specific time of collection depends on the specific GC algorithm.

If there is a variable s inside a method that holds a strong reference to an object, the variable s is saved in the stack, and the real reference content (object) is saved in the heap. When the method runs, it will exit the method stack, the reference s will be destroyed, and the object will be recycled. However, when the S is a global variable, it needs to be assigned null when the object is no longer used, because the objects associated with strong references will not be garbage collected.

Let's look at another one

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