Java reference types are explained in detail

Source: Internet
Author: User

JVM garbage collection has a different approach to different types of references. Java for its object. There is only a citation. It will always exist in memory. Suppose more and more such an object, the amount of memory outside the JVM. The JVM throws a outofmemory error.

Although the implementation details of the garbage collection are controlled by the JVM. The sender is still able to interact with the garbage collector to a certain extent, with the goal of helping the garbage collector manage the memory of the application in a better way. This interaction is the JAVA.LANG.REF package introduced with JDK1.2.

Strong references (strong reference)

In a generic Java program, the most visible is a strong reference (strong reference). As Date date = Newdate (), date is a strong reference to an object.

A strong reference to an object can be passed around in a program. In very many cases, there are multiple references to the same object at a time. The presence of a strong reference limits the time that an object survives in memory.

If object A contains a strong reference to object B. Under normal circumstances, object B will not survive shorter than object A.

Suppose that object A does not explicitly set the reference to object B to NULL, only if object A is garbage collected. Object B does not have a reference to it anymore. Chance of getting garbage collected.

Soft references (soft reference)

Soft references (soft reference) are weaker than strong references in strength and are represented by class SoftReference.

Its role is to tell the garbage collector. which objects in the program are not so important. Can be temporarily reclaimed when memory is low. When there is not enough memory in the JVM, the garbage collector releases objects that are only pointed to by soft references. It is assumed that after all these objects have been freed, the memory is not sufficient to throw a outofmemory error. Soft references are good for creating caches. When the system is running out of memory, the content in the cache can be freed. For example, consider an image editor program. The program will read all the contents of the image file into memory. To facilitate the processing. Users can also open multiple files at the same time. When too many files are opened at the same time, it can cause insufficient memory. Assuming that a soft reference is used to point to the contents of the image file, the garbage collector can reclaim the memory when necessary.


Import Java.lang.ref.softreference;public class ImageData {private String path;private softreference<byte[]> Dataref;public ImageData (String path) {This.path = Path;dataref = new softreference<byte[]> (new Byte[0]);} Private byte[] Readimage () {return new byte[1024 * 1024];//omitted to read file operation}public byte[] GetData () {byte[] DataArray = Datare F.get (); if (DataArray = = NULL | | dataarray.length = = 0) {DataArray = Readimage ();d ataref = new softreference<byte[]> (DataArray);} return DataArray;}}


The-XMX can be used to limit the memory available to the JVM when executing the above program. The object that the soft reference points to may be recycled. When you get the object that the soft reference actually points to by using the Get method, always check that the object is still alive.

Weak references (weak reference)

Weak references (weak reference) are weaker than soft references in strength and are represented by class WeakReference. It does this by referencing an object, but it does not prevent the object from being recycled. Suppose a strong reference is used. Just want the reference to exist. Then the referenced object cannot be recycled.

Weak references do not have this problem.

When the garbage collector executes, the object is recycled, assuming that all references to an object are weak references.

The function of weak references is to solve the coupling relationship between objects brought by strong references in the time of survival. The most common use of weak references is in a collection class, especially in a hash table.

The hash table interface agrees to use whatever Java object is used as a key. When a key-value pair is placed into the hash table. The Hashtable object itself has a reference to these key and value objects.

If such a reference is a strong reference, then only the hash table object itself will survive, including the key and value objects are not recycled. Assuming that a very long-lived hash table contains very many key-value pairs, it is finally possible to consume all the memory in the JVM. The solution to such a situation is to use weak references to refer to these objects so that the key and value objects in the hash table can be garbage collected.

Weakhashmap is available in Java to meet this common need.

Virtual reference (Phantom Reference)


Before you introduce a virtual reference, you should first describe the object termination mechanism (finalization) provided by Java. There is a Finalize method in the object class that is designed to perform some cleanup work before an object is actually recycled. Because Java does not provide the same mechanism as a C + + destructor, it is implemented by the Finalize method.

The problem is that the garbage collector's execution time is not fixed, so the actual execution time of these cleanup tasks is unpredictable. A virtual reference (phantom reference) solves the problem. It is necessary to specify a reference queue when creating a virtual reference phantomreference. After the Finalize method of an object has been called. The virtual reference to this object is added to the queue.

By checking the contents of the queue, you know whether an object is ready to be recycled.

In some cases. The program will need to be notified when an object's accessibility has changed. For example, a strong reference to an object is no longer present, leaving only soft or weak references.

But there is also a need to do some processing of the reference itself. A typical scenario is in a hash table. The reference object is the key object in the Weakhashmap. After the actual object to which it is referenced is garbage collected. You need to remove the key-value pair from the hash table. With the reference queue (Referencequeue), it is convenient to obtain these weakly referenced objects and remove them from the table.

The former soft and weak reference object is added to the queue. Its reference to the actual object will be emptied proactively.

By referring to the queue Poll/remove the method can be non-clogging and the way of plugging separately gets a reference queue object.


Reference:

Gain insight into the JVM

Java in-depth exploration


Java reference types are explained in detail

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.