[Java] Reference types

Source: Internet
Author: User

1) Strong reference: Create an object and assign the object directly to a variable, eg:person person = new Person ("Sunny"); No matter how nervous the system resources are, the strongly quoted objects will never be recycled, even if they are not used in the future.

2) Soft reference: implemented by the SoftReference class,eg:softreference<person> p = new softreference<person> (New person ("Rain")); When the memory is very tense, it will be recycled, other times it will not be recycled, so it is important to determine if it is null before use to determine if he has been recycled.

3) Weak reference:,eg:weakreference<person> p = new weakreference<person> (New person ("Rain") is implemented through the WeakReference class; The system garbage collection must be recycled, regardless of the memory adequacy.

The differences between soft and weak references can be explained using the following example.

Importjava.lang.ref.SoftReference;Importjava.lang.ref.WeakReference; SoftReference<Student> softp =NewSoftreference<student> (NewStudent ("Rain")); WeakReference<Student> WEAKP =NewWeakreference<student> (NewStudent ("Rain")); System.GC ();if(Softp.get () = =NULL) {System.out.println ("Soft GC");}Else{System.out.println ("Soft No GC");} if(Weakp.get () = =NULL) {System.out.println ("WEAKP GC");}Else{System.out.println ("WEAKP No GC");}

Output

Soft No GC
WEAKP GC

Visible soft references are not recycled, and weak references are recycled.

4) Virtual reference: cannot be used alone, it is mainly used to track the state of the object being garbage collected. Using the Phantomreference class and the reference queue Referencequeue class for federated use implementation

[1] http://www.admin10000.com/document/1671.html

[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.