Comprehensive parsing of GC and phantom references in Java _java

Source: Internet
Author: User

There are 4 types of references in Java: Strongreference, SoftReference, WeakReference, and Phantomreference (the legendary Ghost quotes hehe),
These 4 types of references are closely related to GC, so let's look at their definitions and usage scenarios in a way:

1, Strong Reference
Strongreference is the default reference implementation of Java, which survives as long as possible within the JVM and is reclaimed when no object points to it

Java code

Copy Code code as follows:

@Test
public void Strongreference () {
Object referent = new Object ();

/**
* Create strongreference by assigning value
*/
Object strongreference = referent;

Assertsame (referent, strongreference);

referent = null;
System.GC ();

/**
* Strongreference will not be recycled after GC
*/
Assertnotnull (strongreference);
}



2, WeakReference & Weakhashmap
WeakReference, as the name suggests, is a weak reference, when the referenced object no longer has a strong reference within the JVM, the GC weak reference will be automatically recycled


Copy Code code as follows:

@Test
public void WeakReference () {
Object referent = new Object ();
weakreference<object> weakrerference = new weakreference<object> (referent);

Assertsame (referent, Weakrerference.get ());

referent = null;
System.GC ();

/**
* Once there is no strong reference to referent, weak reference is automatically recycled after GC
*/
Assertnull (Weakrerference.get ());
}



Weakhashmap uses WeakReference as a key, and once there is no strong reference to key, Weakhashmap automatically deletes the associated entry after GC


Copy Code code as follows:



@Test


public void Weakhashmap () throws Interruptedexception {


Map&lt;object, object&gt; weakhashmap = new Weakhashmap&lt;object, object&gt; ();


Object key = new Object ();


Object value = new Object ();


Weakhashmap.put (key, value);





Asserttrue (Weakhashmap.containsvalue (value));





key = null;


System.GC ();





/**


* Wait for invalid entries to enter Referencequeue to be cleaned next time gettable is called


*/


Thread.Sleep (1000);





/**


* Once a strong reference to key is not in place, Weakhashmap automatically deletes the associated entry after GC


*/


Assertfalse (Weakhashmap.containsvalue (value));


}





3, SoftReference
The WeakReference feature is basically consistent, and the biggest difference is that SoftReference will retain the reference as long as possible until the JVM is low on memory (virtual machine guarantee), which makes softreference very suitable Combined Cache Application


Copy Code code as follows:

@Test
public void SoftReference () {
Object referent = new Object ();
softreference<object> softrerference = new softreference<object> (referent);

Assertnotnull (Softrerference.get ());

referent = null;
System.GC ();

/**
* Soft references is recycled only before the JVM OutOfMemory, so it is ideal for caching applications
*/
Assertnotnull (Softrerference.get ());
}



4, Phantomreference
As the protagonist of this article, Phantom Reference (phantom Reference) is very different from WeakReference and SoftReference because its get () method always returns null, which is the origin of its name.

Java code

Copy Code code as follows:

@Test
public void Phantomreferencealwaysnull () {
Object referent = new Object ();
phantomreference<object> phantomreference = new Phantomreference<object> (referent, New ReferenceQueue <Object> ());

/**
* Phantom Reference's Get method returns Null forever
*/
Assertnull (Phantomreference.get ());
}



As you may ask, what is the use of a reference that returns null forever, notice the second argument when constructing phantomreference referencequeue (in fact WeakReference &amp; SoftReference can also have this parameter),


The only use of phantomreference is to track when Referent is Enqueue to Referencequeue.

5, Rererencequeue
When a weakreference begins to return null, the object it points to is ready to be reclaimed, and you can do some proper cleanup work. Passing a referencequeue to a Reference constructor, when the object is reclaimed, the virtual opportunity automatically inserts the object into the Referencequeue, and Weakhashmap uses Referencequeue to clear the key There are no strong references to entries.

Java code

Copy Code code as follows:



@Test


public void Referencequeue () throws Interruptedexception {


Object referent = new Object ();


referencequeue&lt;object&gt; referencequeue = new referencequeue&lt;object&gt; ();


weakreference&lt;object&gt; weakreference = new Weakreference&lt;object&gt; (referent, referencequeue);





Assertfalse (weakreference.isenqueued ());


reference&lt;? Extends object&gt; polled = Referencequeue.poll ();


Assertnull (polled);





referent = null;


System.GC ();





Asserttrue (weakreference.isenqueued ());


reference&lt;? Extends object&gt; removed = Referencequeue.remove ();


Assertnotnull (removed);


}





6, phantomreference vs WeakReference
Phantomreference has two benefits, one of which allows us to know exactly when objects are removed from memory, and this feature can be used in special requirements (such as distributed GC, Xwork, and Google-guice also use Phant Omreference has done some cleanup work).

Second, it avoids some of the fundamental problems that finalization brings, and the only effect mentioned above phantomreference is to track when Referent is enqueue to Referencequeue, but Weakrefere NCE also has a corresponding function, the difference between the two in the end?

This is about the Finalize method of object, which is invoked before the GC executes, if an object overloads the Finalize method and intentionally creates its own strong reference within the method, which causes the GC to fail to recycle the object and possibly cause any GC, the final knot It is obvious that there are many garbage in the JVM but OutOfMemory, using phantomreference can avoid this problem, because phantomreference is recycled after the Finalize method is executed, which means that it is not possible at this time Get the original quote, there will be no such problems, of course, this is a very extreme example, generally will not appear.

7, contrast

Use When
Soft vs Weak vs Phantom References
Type Purpose gced Implementing Class
Strong Reference An ordinary reference. Keeps objects alive as long as they are referenced. Normal reference. Any object is pointed to can reclaimed. Default
Soft Reference Keeps objects alive provided there enough ' s memory. To keep objects alive even after clients have removed their references (memory-sensitive caches), in case clients start as King for them again by key. After a-a-GC pass, the JVM decides it still needs to reclaim. Java.lang.ref. SoftReference
Weak Reference Keeps objects alive only while they ' re in use (reachable) by clients. Containers that automatically delete objects no longer in use. After GC determines the object was only weakly reachable Java.lang.ref. WeakReference
Java.util. Weakhashmap
Phantom Reference Lets you finalization but before the "space is reclaimed" (replaces or augments the use ofFinalize ()) Special Clean up processing After finalization. Java.lang.ref. phantomreference

8. Summary
general applications do not involve Reference programming, but knowing this knowledge can help understand how GC works and performance tuning, It may be useful to implement some of the basic infrastructure such as caching, and hopefully this article will help.

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