4 kinds of Java reference Shallow solution

Source: Internet
Author: User
Tags java reference

In a recent study of Java cache implementations, it was found that soft references (softreference) were not understood, and the JDK documentation, code, and several articles were consulted. Make a summary, if there is a mistake, please correct me.

There are two reasons why you want to learn about several types of references in Java:

    • Understand the relationship between Java cache implementations, learning Java references, and Java garbage collection mechanisms
      Memory resources are limited and need to be used rationally. The cache is not simply HashMap, and Java references are closely related to the Java garbage collection mechanism.
    • Avoid incorrect use of Java references
      A colleague puts 5000+ transaction data into a hashmap, pointing to the HashMap with a spring Singleton Bean's global properties. Using this technique in large quantities, it is very quick to report out of memory. The larger memory also jiabuzhu the wrong use of memory. Understanding the principles helps us to minimize or not make low-level mistakes.
The relationship between Java reference and Java garbage collection mechanism

When the Java Virtual Machine (JVM) thinks that memory is insufficient, it triggers a garbage collection operation (GC), cleans up unused objects, and frees up memory. But how do you infer if an object is rubbish? One of the methods is to calculate the number of references to the object, assuming that the number of references is 0, then the object is garbage (the thread object is the exception), otherwise the utility cannot be recycled. But what if the object with the reference number 0 is recycled, or does not meet the memory requirements? Java divides references into 4 types, and the garbage collector attempts to reclaim objects that have only weak references.

According to the reference of an object can reach (Reachable) strength, from strong to weak divided into 5 categories, such as the following:

    • Strong to reach (strong Reachable)
      Within a thread, there is no need to refer directly to the newly created object, which is strongly accessible.
    • Soft to reach (Soft Reachable)
      Not strong, but through a soft reference (SoftReference) can be reached.
    • Weak to reach (Soft Reachable)
      It is neither strong nor soft, but can be reached by a weak reference (WeakReference).
    • Virtual up to (Phantom Reachable)
      Neither strong nor soft, nor weakly accessible, but through a virtual reference (Phantomreference) can be reached.
    • Not reached (unreachable)
      No matter what references point to the object.

Better and easier to understand is that the Java garbage collector prioritizes objects that are low in strength. There are also two important points:

    • The strong can never be cleaned up.
    • The JVM guarantees to clean up all soft reference objects before throwing out of memory
4 Types of Java references

When implementing a caching system, assuming that all use strong references, then you need to manually clear some references (reference set NULL), or sooner or later throw out of memory errors. The only reason the cache system introduces a weak or soft reference is to leave the reference clear to the Java garbage collector and the cache program to stay out of it.

Several weak references are used in a similar way. The following are 4 reference types, respectively.

Strong references (strongreference)

We usually declare that variables use strong references, more than 99% of ordinary systems are strong references. ExampleString s = "Hello World"

Weak references (WeakReference)

When the garbage collector decides to reclaim a soft object at some point, it cleans up the soft reference and optionally holds the reference to a reference queue (Referencequeue).

Soft references (SoftReference)

Similar to weak references, just Java virtual opportunity to try to make soft references longer survival time, forced to clean up.

Virtual Reference (Phantomreference)

This is more flexible than the finalize mechanism in object, which is used only to deal with resource cleanup issues. The Get method always returns a Null,java virtual machine that is not responsible for cleaning up virtual references, but it puts virtual references inside the reference queue.

Example of two test specimens

With HashMap, an out of memory error is reported.

public static void Main (string[] args) {map<string, string> list = new hashmap<string, string> (); Long i = 1;WH Ile (I < 100000000L) {list.put (string.valueof (i), "JDJJDJJJJJJJJJJ%%%%%%%%JJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKJJJJJJ "+" JJJKKKKKHDDDJDJDJDJDJDJDJDJJDJDJDJDJDJDJJDJDJDJDJJDJDJJJJJJJJJ "+" JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ "+" JJJJJJJJJJJJJJJJJJJJJJJJJJJJ ");// Test whether the first one still survives if (i% 100000 = = 0) {System.out.println (List.get (string.valueof (1)));} i++;}}

With Weakhashmap, out of memory errors are not reported.

public static void Main (string[] args) {map<string, string> list = new weakhashmap<string, string> (); Long i = 1;while (I < 100000000L) {list.put (string.valueof (i), "jdjjdjjjjjjjjjj%%%%%%%% JJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKJJJJJJ "+" JJJKKKKKHDDDJDJDJDJDJDJDJDJJDJDJDJDJDJDJJDJDJDJDJJDJDJJJJJJJJJ "+" JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ "+" JJJJJJJJJJJJJJJJJJJJJJJJJJJJ ");// Test whether the first one still survives if (i% 100000 = = 0) {System.out.println (List.get (string.valueof (1)));} i++;}}


Summary

In the Java language, arrays, lists, maps, and so on, have a reference to each object inside, and in case of big data, be careful about memory leaks. Weak references are only suitable for special scenarios such as cache, and strong references are used for objects that must not be recycled by the garbage collector in Java.

References connection
    • Understanding Weak References
    • JDK Java.lang.ref Pack documentation files, and class descriptions

4 kinds of Java reference Shallow solution

Related Article

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.