Four types of references in Java

Source: Internet
Author: User

1. Strong references (strong Reference) are "strongest" in four references in Java, and the objects we create by using the new keyword are strongly referenced, as in the following code:
person person = new person ();
The person in it is a strong reference and is not reclaimed by the garbage collector until it is no longer in use. When memory is low, but it is still in use, the garbage collector does not reclaim its referenced objects, and the JVM prefers to report "Memory leak error (OUTOFMEMORYERROR)", and the terminating program does not reclaim the objects associated with this reference.

person person = new person ();
softreference <person > personsoftreference = new softreference (person);

person person = new person ();
weakreference <person > personweakreference = new weakreference (person);

4, virtual reference (Phantom Reference) is "The weakest" of a reference, optional reference, can also be understood as almost no reference, at any time may be garbage collector (garbage collection) recycling; Once scanned by the garbage collector (garbage collection), it is instantly recycled. Primarily used to track the behavior of the garbage collector. A virtual reference, like a weak reference, is typically used with a reference queue (Reference queue), and when the garbage collector (garbage collection) reclaims the object associated with a weak reference, it is placed in the reference queue, and we can listen to the queue as well. Once a new virtual reference is put in, execute our scheduled program. The sample code is as follows
person person = new person ();
  phantomreference<Person> personphantomreference = new phantomreference(person);
The personsoftreference is called a virtual reference, which refers to the object of the new person ();

Four types of references in Java

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