Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The difference of four references in Java language

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "four kinds of citation differences in Java language". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The difference between four kinds of citations

In fact, the difference between the four citations is that they are handled differently when GC. To sum up in one sentence: if an object is GC Root reachable, the strong reference will not be recycled, the soft reference will be recycled when the memory is low, and the weak reference will be recycled the first time the object GC.

If the GC Root is unreachable, any reference will be recycled

Virtual references are special, which means that there are no references and will not affect the life cycle of the object, but you can receive a system notification when the object is reclaimed by the collector.

Let's take a look at the performance of the four references in the face of GC and their common uses. First, set the parameters of JVM:

-Xms20M-Xmx20M-Xmn10M-verbose:gc-XX:+PrintGCDetails

Strong citation

This is the quote that we usually use most often. As long as the object GC Root is reachable when GC, it will not be recycled. If the JVM runs out of memory, throw the OOM directly. For example, the following code throws an OutOfMemoryError:

Public static void main (String [] args) {

List list = new LinkedList ()

For (int I = 0; I < 21; iTunes +) {

List.add (new byte [1024 * 1024])

}

}

Soft reference

Soft references, when GC, if GC Root is reachable, if there is enough memory, it will not be reclaimed; if there is not enough memory, it will be reclaimed. Change the above example to a soft reference and it will not be OOM:

Public static void main (String [] args) {

List list = new LinkedList ()

For (int I = 0; I < 21; iTunes +) {

SoftReference softReference = new SoftReference (new byte [1024 * 1024])

List.add (softReference)

}

}

Let's modify the program to print out the difference before and after GC:

Public static void main (String [] args) {

List list = new LinkedList ()

For (int I = 0; I < 21; iTunes +) {

SoftReference softReference = new SoftReference (new byte [1024 * 1024])

List.add (softReference)

System.out.println ("before gc:" + softReference.get ())

}

System.gc ()

For (SoftReference softReference: list) {

System.out.println ("after gc:" + softReference.get ())

}

}

You will find that the printed logs have a value before GC, while after GC, some of them will be null, indicating that they have been recycled.

The maximum heap we set is 20m. If you change the number of cycles to 15, you will find that the log printed out is not null after GC. However, through the-verbose:gc-XX:+PrintGCDetails parameter, you can see that JVM did GC several times, but it was not reclaimed because there was enough memory.

Public static void main (String [] args) {

List list = new LinkedList ()

For (int I = 0; I < 15; iTunes +) {

SoftReference softReference = new SoftReference (new byte [1024 * 1024])

List.add (softReference)

System.out.println ("before gc:" + softReference.get ())

}

System.gc ()

For (SoftReference softReference: list) {

System.out.println ("after gc:" + softReference.get ())

}

}

So the common use of soft references comes out: caching. Especially those who want the cache to last longer.

Weak reference

Soft references are recycled as long as GC occurs on this object.

Change the above code to a soft reference, and you will find that the printed logs are all null after GC.

Public static void main (String [] args) {

List list = new LinkedList ()

For (int I = 0; I < 15; iTunes +) {

WeakReference weakReference = new WeakReference (new byte [1024 * 1024])

List.add (weakReference)

System.out.println ("before gc:" + weakReference.get ())

}

System.gc ()

For (WeakReference weakReference: list) {

System.out.println ("after gc:" + weakReference.get ())

}

}

So weak references are also suitable for caching, but because they are recycled whenever GC occurs, the survival time is much shorter than soft references and is usually used to do some very temporary caching.

We know that WeakHashMap manages entry internally through weak references. Its key is a "weak key", so in GC, its corresponding key-value pair is also deleted from the Map.

Tomcat there is a ConcurrentCache, using WeakHashMap, combined with ConcurrentHashMap, to achieve a thread-safe cache, interested students can study the source code, the code is very concise, plus all the comments, only 59 lines.

Entry in the static inner class ThreadLocalMap in ThreadLocal is an inherited class for WeakReference.

Use weak references to let ThreadLocalMap know whether the ThreadLocal object has expired, that is, it becomes garbage, then the data in the Map it controls is useless, because the outside world can no longer access it, and then decides to erase the relevant value objects in the Map, the reference to the Entry object, to ensure that the Map is always kept as small as possible.

Virtual reference

The design of the virtual reference is somewhat different from the above three references, it does not affect the GC, but rather to receive a system notification when the object is GC.

So how was it informed? A virtual reference must cooperate with ReferenceQueue. When GC prepares to recycle an object, if it finds that it still has a virtual reference, it will add the virtual reference to the associated ReferenceQueue before recycling.

So how does NIO use virtual references to manage memory?

DirectBuffer requests a piece of memory directly from the Java heap, which is not directly managed by JVM GC, which means that the memory is not directly manipulated in the GC algorithm. The GC of this memory is because DirectBuffer objects in the Java heap are cleaned up through a notification mechanism after they are GC.

There is a Cleaner inside the DirectBuffer. This Cleaner is a subclass of PhantomReference. When the DirectBuffer object is reclaimed, the PhantomReference is notified. Then ReferenceHandler calls the tryHandlePending () method for pending processing. If the pending is not empty, the DirectBuffer is recycled, and you can call clean () of Cleaner for recycling.

The code for the above method is in the Reference class. Interested students can take a look at the source code of that method.

Summary

These are the differences between the four references in Java. Generally speaking, strong quotes are known to us all, but virtual references are rarely used. The difference between a soft reference and a weak reference lies in the timing of recycling: when a soft reference GC, it will be recycled if there is not enough memory, and a weak reference will be recycled as long as it takes only one GC.

This is the end of the content of "four kinds of citation differences in Java language". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report