Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use four reference types in JAVA Springboot

Shulou Source: shulou.com Published: 2022-06-03 19:19:48 09月17日 Update

Editor to share with you how to use the four citation types in JAVA Springboot, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!

Concept introduction

Different reference types mainly reflect the different reachable states of objects and their impact on garbage collection.

01. Strong citation

This is the normal object we created ~ when the object is explicitly assigned to null, or when it is not referenced by other living objects, it becomes the target of the garbage collector, waiting to be collected

02. Soft reference

Soft reference (SoftReference), which is reclaimed when there is insufficient memory

such as

After being recycled, null will be printed here instead of Java4ye

03. Weak reference

Weak reference (WeakReference), when the garbage collector carries out garbage collection, it will be collected by the garbage collector regardless of whether the memory is sufficient or not

such as

After being recycled, null will also be printed here instead of Java4ye

04. Virtual reference

Virtual reference (ReferenceQueue), which can also be recycled at any time, acts more like a tag. When an object is recycled, it is not null, but note that whenever you call the get method of a virtual reference, you can only get a null value.

The only purpose of setting a virtual reference association for an object is to receive a system notification when the object is reclaimed by the collector--

Here is an example of http://www.javashuo.com/article/p-zyvdcbhl-nb.html 's article.

User user = new User (1, "Java4ye"); ReferenceQueue userReferenceQueue = new ReferenceQueue (); / / create a virtual reference to the User object PhantomReference phantomReference = new PhantomReference (user, userReferenceQueue); / / remove the strong reference user = null;System.out.println (phantomReference.get ()); / / manually trigger GCSystem.gc (); System.out.println ("GC:" + phantomReference.get ()); Reference

Tags: Objects garbage source code articles types examples accessibility that is states levels collectors differences functions memory content meaning threads facets text collectors Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno MariaDB Xiaomi MySQL Shulou Technology