Four types of references in Java (strong, soft, weak, and virtual references to objects)

Source: Internet
Author: User
Tags garbage collection

strong, soft, weak, and virtual references to objects
In previous versions of JDK 1.2, if an object was not referenced by any variable, the program could no longer use the object. In other words, only the object is in a reachable state and the program can use it. Starting with JDK version 1.2, the reference to the object is divided into 4 levels, giving the program more flexibility to control the life cycle of the object. These 4 levels, from highest to lowest, are: Strong references, soft references, weak references, and virtual references.

The

⑴ strong reference (strongreference)
Strong reference is the most commonly used reference. If an object has a strong reference, the garbage collector will never reclaim it. When memory space is low, the Java virtual machine would rather throw a outofmemoryerror error, cause the program to terminate abnormally, and not recycle the strongly referenced object to solve the out-of-memory problem.   ps: The strong reference is actually the meaning of our usual a A = new A ().

⑵ Soft Reference (SoftReference)
If an object has only a soft reference, there is enough memory space and the garbage collector will not recycle it; if there is not enough memory, the memory of those objects will be reclaimed. The object can be used by the program as long as the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive caching (shown below for example). A
Soft reference can be used in conjunction with a reference queue (Referencequeue), and if the soft reference refers to an object that is reclaimed by the garbage collector, the Java Virtual machine adds the soft reference to the reference queue associated with it.

⑶ Weak references (weakreference)
Weak references differ from soft references in that an object with only a weak reference has a shorter life cycle. When the garbage collector thread scans the area of memory it governs, it reclaims its memory whenever it discovers an object that has only a weak reference, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a very low priority thread, it is not necessarily easy to find those objects that have only weak references. A
Weak reference can be used in conjunction with a reference queue (Referencequeue), and the Java virtual machine adds the weak reference to the reference queue associated with it if the object referenced by the weak reference is garbage collected. The

⑷ virtual Reference (phantomreference)
Virtual Reference, as the name suggests, is a dummy, unlike several other references, which do not determine the life cycle of an object. If an object holds only a virtual reference, it is likely to be reclaimed by the garbage collector at any time, as without any reference. A
Virtual reference is primarily used to track activities that an object is reclaimed by the garbage collector. One difference between a virtual reference and a soft reference and a weak reference is that a virtual reference must be used in conjunction with a reference queue (Referencequeue). When the garbage collector is ready to reclaim an object, if it finds a virtual reference, it adds the virtual reference to the associated reference queue before reclaiming the object's memory.

Referencequeue queue = new referencequeue ();

Phantomreference PR = new phantomreference (object, queue);
A program can determine whether a referenced object will be garbage collected by determining whether a virtual reference has been added to the reference queue. If the program finds that a virtual reference has been added to the reference queue, you can take the necessary action before the memory of the referenced object is reclaimed.


Using soft references to build cache of sensitive data
1 Why you need to use soft references
First, let's look at an example of an employee information query system. We will use a Java language-implemented Employee information query system to query employee personnel file information stored in disk files or databases. As a user, there's a good chance we'll have to go back and look at the employee profile information we've seen a few minutes or even a few seconds ago (again, we often use the back button when browsing a Web page). There are usually two ways to implement the program: one is to keep the employee information in memory in the past, and each Java object that stores employee profile information has a lifecycle throughout the application, and the other is when the user starts looking at other employees ' file information, Ends a reference to a Java object that stores information about the currently viewed employee profile, allowing the garbage collection thread to reclaim the memory space it occupies, and reconstruct the employee's information when the user again needs to browse the employee's profile information. Obviously, the first implementation will cause a lot of memory waste, and the second implementation is flawed that even if the garbage collection thread has not been garbage collected, the object containing the employee profile information is still intact in memory and the application is rebuilding an object. We know that accessing disk files, accessing network resources, querying databases, and so on are all important factors that affect application performance, and if you can retrieve references to Java objects that have not been reclaimed, you will reduce unnecessary access and greatly increase the speed of your program.

2 If you use a soft reference
The SoftReference feature is that an instance of it holds soft references to a Java object that does not prevent garbage collection threads from reclaiming the Java object. That is, once SoftReference has saved a soft reference to a Java object, the Get () method provided by the SoftReference class returns a strong reference to the Java object before the garbage thread reclaims the Java object. Also, once the garbage thread reclaims the Java object, the Get () method returns NULL.
Look at the following code:

MyObject aRef = new MyObject ();

SoftReference asoftref = new softreference (AREF);


At this point, there are two reference paths for this MyObject object, one is a soft reference from the SoftReference object, a strong reference from the variable areference, so the MyObject object is a strong object.
Immediately, we can end the strong reference to this MyObject instance by areference:

AREF = null;


Thereafter, the MyObject object becomes a soft and accessible object. If the garbage collection thread does memory garbage collection, the object is not always preserved because a softreference reference to the object is made. Garbage collection Threads of Java virtual machines discriminate between soft and object and other generic Java objects: Soft and object cleanup is determined by the garbage collection thread according to the memory requirements for its particular algorithm. That is, the garbage collection thread reclaims the soft objects before the virtual machine throws the OutOfMemoryError, and the virtual opportunity takes as much priority as possible to reclaim the soft objects that are unused for a long time, and the "new" soft objects that have just been built or just used will be kept as much as possible by the virtual machine. Before we recycle these objects, we can reclaim the strong reference to the instance by:
myobject anotherref= (MyObject) asoftref.get ();  

. After the recycle, the call to the Get () method can only be null.

3 uses Referencequeue to purge SoftReference
        that has lost the soft reference object as a Java object, In addition to having the particularity of saving soft references, the SoftReference object also has the generality of Java objects. So, when the soft and the object is recycled, although the get () method of the SoftReference object returns NULL, the SoftReference object no longer has the value of being, and requires an appropriate cleanup mechanism, Avoid the memory leaks caused by a large number of SoftReference objects. Referencequeue is also available in the Java.lang.ref bag. If you are creating a SoftReference object, you use a Referencequeue object as a parameter to provide the softreference with a constructor, such as:

Referencequeue queue = new referencequeue (); SoftReference ref = New
SoftReference (amyobject, queue);

The SoftReference object referenced by ref is included in Referencequeue, while the amyohject referenced by this softreference is reclaimed by the garbage collector. That is, the object that is saved in the Referencequeue is the reference object, and it is the reference object that has lost the object it is soft referenced. Also seen from the name of Referencequeue, it is a queue, and when we call its poll () method, if the queue is not an empty queue, the reference object in front of the queue will be returned.
At any time, we can call the Referencequeue poll () method to check if there is a strong object that it cares about and that it is recycled. If the queue is empty, a null is returned, otherwise the method returns a reference object that precedes the queue. Using this method, we can check which softreference the soft referenced object has been reclaimed. So we can get rid of the SoftReference object that lost the soft reference object. The usual ways are:

SoftReference ref = NULL;

while (ref = (EMPLOYEEREF) q.poll ())!= null) {

Clear ref

}

Original: Four types of references in Java
Http://www.pocketcn.com/forum-viewthread-tid-1661-fromuid-1477.html


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.