Java reference types

Source: Internet
Author: User

Problem:

Before JDK1.2, objects had only "referenced" and "not referenced" states, and for some objects that were "useless now, but not sure if they were useful later", in such a scenario, they could only be defined as "not referenced" and therefore garbage collected.

Once the object is used in the future, the object cannot be found.

We want to describe a class of objects that are kept in memory if there is sufficient memory space, and if the memory after garbage collection is still very tight, the memory consumed by those objects is freed. (such as the caching function of the system)

4 Types of references:

Java introduced 4 types of references after 1.2: Strong references (strong Reference), soft references (Soft Reference), weak references (Weak Reference), virtual references (Phantom Reference). The strength of 4 references decreases in turn.

Strong reference: is a common reference, such as StringBuffer sb = new StringBuffer (), as long as a strong reference exists, it will not be garbage collected;

Soft Reference: as long as the memory space is sufficient, soft-referenced objects will not be released, and when the system will be a memory overflow, the soft-referenced objects will be included in the recycling scope, JDK1.2 using the SoftReference class to implement soft reference;

Weak references: weak references do not affect the life cycle of an object, and the garbage collector treats weakly referenced objects as normal objects (which can be recycled as long as there are no strong references); JDK1.2 uses the WeakReference class to implement weak references;

Virtual Reference: A virtual reference does not affect the life cycle of an object, the object instance cannot be obtained through a virtual reference, and the purpose of creating a virtual reference is to receive a system notification when the object is reclaimed by the garbage collector. JDK1.2 uses the Phantomreference class to implement virtual references.

Java reference types

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.