Four types of references in Java

Source: Internet
Author: User
Strong references, soft references, weak references, virtual references: Different reference types are mainly represented on the GC
  1. Strong reference: If an object has a strong reference, it will not be reclaimed by the garbage collector. Even if there is not enough memory space, the JVM does not reclaim it, but instead throws a outofmemoryerror error that causes the program to terminate unexpectedly. If you want to break the association between a strong reference and an object, you can explicitly assign a reference to NULL, so that the JVM reclaims the object at the appropriate time

  2. Soft references: When using soft references, if there is enough memory space, soft references can continue to be used without being reclaimed by the garbage collector, and soft references are reclaimed by the garbage collector only when there is insufficient memory.

  3. Weak reference: An object with a weak reference has a more ephemeral life cycle. Because when the JVM is garbage collected, weak references are recycled whenever a weak reference object is found, regardless of whether the current memory space is sufficient. However, because the garbage collector is a low-priority thread, it is not always possible to quickly discover weak reference objects

  4. Virtual reference: As the name implies, is the form of a dummy, if an object only holds a virtual reference, then it is equivalent to no reference, at any time may be reclaimed by the garbage collector.

What is the difference between WeakReference and softreference?

This is explained in four reference types, which can be described briefly: although WeakReference and SoftReference both contribute to the efficiency of GC and memory, WeakReference, once the last strong reference is lost, is recycled by GC, and the soft References, although not prevented from being recycled, can be deferred until the JVM is running out of memory.

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.