The distinction between four types of references in Java

Source: Internet
Author: User
Tags object object

Strong references (strongreference)

Strong references are commonly found in program code, such as the following code in which both object and Str are strong references:

12 Object object = newObject();String str = "hello";

as long as an object has a strong reference associated with it, the JVM must not reclaim the object, even if the JVM prefers to throw a outofmemory error in case of low memory . For example, the following code:

12345678910 public class Main {    public static void main(String[] args) {        new Main().fun1();    }         public void fun1() {        Object object = new Object();        Object[] objArr = new Object[1000];    }}

When running to object[] Objarr = new object[1000]; when there is not enough memory, the JVM throws an oom error and does not reclaim the object pointed to by object. Note, however, that when Fun1 runs out, both object and Objarr are no longer present, so the objects they point to will be reclaimed by the JVM.

If you want to break the association between a strong reference and an object, you can display the reference assignment to NULL, so that the JVM reclaims the object at the appropriate time.

Soft References (softreference)

Soft references are used to describe some useful but not necessary objects, which are represented in Java by the Java.lang.ref.SoftReference class. For objects associated with soft references, the JVM reclaims the object only when there is insufficient memory . Therefore, this is a good way to solve the problem of oom, and this feature is well suited for caching: such as Web caching, image caching, and so on.

A soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is reclaimed by the JVM, the soft reference is added to the reference queue associated with it. The following is an example of use:

123456789101112 import java.lang.ref.WeakReference; public class Main {    public static void main(String[] args) {             WeakReference<String> sr = new WeakReference<String>(new String("hello"));                 System.out.println(sr.get());        System.gc();                //通知JVM的gc进行垃圾回收        System.out.println(sr.get());    }}
Weak references (weakreference)

Weak references are also used to describe non-essential objects, and when the JVM is garbage collected, the objects associated with the weak references are reclaimed regardless of the adequacy of the memory. In Java, it is represented by the Java.lang.ref.WeakReference class. The following are examples of use:

123456789101112 import java.lang.ref.WeakReference; public class Main {    public static void main(String[] args) {             WeakReference<String> sr = new WeakReference<String>(new String("hello"));                 System.out.println(sr.get());        System.gc();                //通知JVM的gc进行垃圾回收        System.out.println(sr.get());    }}
Virtual Reference (phantomreference)

A virtual reference differs from the previous soft reference and weak reference, and it does not affect the life cycle of the object. Represented in Java with the Java.lang.ref.PhantomReference class. If an object is associated with a virtual reference, it can be reclaimed by the garbage collector at any time, as with no reference to it.

Note that a virtual reference must be used in association with a reference queue, and when the garbage collector is ready to reclaim an object, if it finds a virtual reference, it adds the virtual reference to the reference queue associated with it. The program can see if the referenced object is going to be garbage collected by judging whether the reference queue has been added to the virtual reference. If the program discovers that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is reclaimed.

further understanding of soft and weak references

For strong references, we usually use them when writing code. And for the other three types of references, the most used is soft and weak references, these 2 kinds of similarities and differences. They are all used to describe non-essential objects, but objects associated with soft references are recycled only when they are out of memory, and objects associated with weak references are always recycled when the JVM is garbage collected . For the above features, Soft references are appropriate for caching, allowing the JVM to reclaim memory when insufficient memory is available, and weak references can be used to prevent memory leaks in callback functions. because the callback function is often an anonymous inner class, implicitly holds a reference to the external class, so if the callback function is called back in another thread, then if the external classes need to be recycled, then the memory leaks because the anonymous inner class holds a strong reference to the external classes.

Reference Blog: Haizi Sylvanas goddess

The distinction between four types of references in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.