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

What are the reference types in Java

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly shows you "which citation types are in Java", the content is simple and clear, and I hope it can help you solve your doubts. Let me lead you to study and learn this article "which citation types are in Java".

What are the reference types in Java?

The reference types in Java are divided into strong references, soft references, weak references, and virtual references.

1. Strong quotation

There is no reference to this object, garbage collection will collect

Package git.snippets.juc;import java.io.IOException;public class NormalRef {public static void main (String [] args) throws IOException {mm = new M (); m = null; System.gc (); System.in.read ();} static class M {M () {} @ Override protected void finalize () throws Throwable {System.out.println ("finalized") }} 2. Soft reference

When an object is pointed to by a soft reference, it will be recycled only when the system memory is insufficient and can be used as a cache (such as caching large pictures).

The example code is as follows: note: when you execute the following method, you need to set VM options to-Xms20M-Xmx20M.

Package git.snippets.juc;import java.io.IOException;import java.lang.ref.SoftReference;import java.util.concurrent.TimeUnit / * heap will not fit. At this time, the system will garbage collect. If not, soft references will be killed * soft references are suitable for caching * for example, Vm options needs to be set to:-Xms20M-Xmx20M * / public class SoftRef {public static void main (String [] args) throws IOException {SoftReference reference = new SoftReference (new byte [1024 * 1024 * 10]); System.out.println (reference.get ()) System.gc (); try {TimeUnit.SECONDS.sleep (2);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println (reference.get ()); byte [] bytes = new byte [1024 * 1024 * 10]; System.out.println (reference.get ()); System.in.read ();}}

When the above code executes System.out.println (reference.get ()) for the first time, since the maximum and minimum values of the heap are all 20m, and our allocated byte array is 10m, which does not exceed the maximum heap memory, garbage collection is performed and the soft reference is not collected, followed by a call to byte [] bytes = new byte [1024 * 1024 * 10] When 10m of memory is allocated again, the heap memory has exceeded the maximum set value and will be reclaimed, so the last step System.out.println (reference.get ()); cannot get the data.

3. Weak citation

As long as garbage is recycled, it will be recycled. If there is a strong reference to the object in the weak reference, if the strong reference disappears, the object should be recycled. It is usually used in containers.

The code example is as follows:

Package git.snippets.juc;import java.lang.ref.WeakReference;import java.util.HashMap;import java.util.concurrent.TimeUnit;/** * weak references will be recycled by gc * ThreadLocal applications, caching applications, WeakHashMap * / public class WeakRef {public static void main (String [] args) {WeakReference reference = new WeakReference (new T ()); System.out.println (reference.get ()); System.gc () System.out.println (reference.get ());} static class T {T () {} @ Override protected void finalize () {System.out.println ("finalized");}

If the GC is executed once, the value obtained by reference.get () is empty.

4. Usage scenarios of weak references

A typical application scenario for weak references is ThreadLocal. Here is a brief introduction to ThreadLocal

Set method:

Public void set (T value) {Thread t = Thread.currentThread (); ThreadLocalMap map = getMap (t); if (map! = null) map.set (this, value); else createMap (t, value);}

Get method:

Public T get () {Thread t = Thread.currentThread (); ThreadLocalMap map = getMap (t); if (map! = null) {ThreadLocalMap.Entry e = map.getEntry (this); if (e! = null) {@ SuppressWarnings ("unchecked") T result = (T) e.value; return result }} return setInitialValue ();}

ThreadLocalMap is a member variable of the current thread, so other threads cannot read the ThreadLocal value set by the current thread.

ThreadLocal.ThreadLocalMap threadLocals = null

The main application scenarios of ThreadLocal

Scenario 1: each thread needs an exclusive object: suppose there are 100 threads that need to use the SimpleDateFormat class to deal with the date format. If you share a SimpleDateFormat, there will be thread safety problems, resulting in data errors, and if you add locks, it will degrade performance. Using ThreadLocal to save a local SimpleDateFormat for each thread can ensure both thread safety and performance requirements.

Scenario 2: global variables are saved inside each thread to avoid the trouble of passing parameters: suppose the function of a thread is to get the front-end user information and execute the business logic of Service1, Service2, Service3 and Service4 layer by layer, in which each business layer will use user information. A solution is to pass User information objects as parameters layer by layer, but this will lead to code redundancy and is not conducive to maintenance. At this point, you can put the User information object into the Threadlocal of the current thread and become a global variable. In each business layer, you can directly obtain it from the Threadlocal when you need to use it.

Scenario 3: the declarative transaction of Spring, the database connection is written in the configuration file, and multiple methods can support a complete transaction, ensuring that multiple methods use the same database connection (actually put in ThreadLocal)

After a brief introduction to ThreadLocal, we can take a closer look at one of the internal principles of ThreadLocal. As mentioned earlier, the set method of ThreadLocal actually inserts a record into a threadLocals table of the current thread, and the records in this table exist in an Entry object, which has a key and a value, and key is the ThreadLocal object of the current thread.

Static class Entry extends WeakReference

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

Development

Wechat

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

12
Report