Java References summary--strongreference, SoftReference, WeakReference, phantomreference
1 Introduction to Java references
Java introduced 4 types of references starting with version 1.2, and these 4 reference levels are from highest to lowest:
Strong references > Soft references > Weak references > virtual references
⑴ Strong references (strongreference)
Strong references are the most commonly used references. If an object has a strong reference, the garbage collector will never recycle it. When there is not enough memory space, the Java virtual Machine prefers to throw a outofmemoryerror error, which causes the program to terminate abnormally, and does not rely on random recycling of strongly referenced objects to resolve out-of-memory issues.
⑵ Soft Reference (SoftReference)
If an object has only soft references, enough memory space is available, the garbage collector does not recycle it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caches.
A soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is reclaimed by the garbage collector, the Java Virtual machine will add the soft reference to the reference queue associated with it.
⑶ Weak references (weakreference)
The difference between a weak reference and a soft reference is that an object with only a weak reference has a shorter life cycle. As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is reclaimed, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references.
A weak reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the weak reference is garbage collected, the Java virtual machine adds the weak reference to the reference queue associated with it.
⑷ Virtual Reference (phantomreference)
"Virtual Reference", as the name implies, is a dummy, unlike several other references, a virtual reference does not determine the object's life cycle. If an object holds only virtual references, it can be reclaimed by the garbage collector at any time, just as there are no references.
Virtual references are primarily used to track activities that objects are reclaimed by the garbage collector. One difference between a virtual reference and a soft reference and a weak reference is that the virtual reference must be used in conjunction with the reference queue (Referencequeue). When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory.
Because of the close relationship between references and memory reclamation. Below, we have an understanding of memory recycling through an instance, and then further deepen the understanding of references by referencing instances.
2 Memory Recycling
creates a public class mydatethat overwrites the Finalize () function: Prints the printed information in Finalize () for easy tracking.
Description: The Finalize () function is executed when the JVM reclaims memory, but the JVM does not guarantee that finalize () will be called when the memory is reclaimed.
The MyDate code is as follows:
PackageCom.skywang.java;Importjava.util.Date; Public classMyDateextendsDate {/**creates a new instance of MyDate*/ Publicmydate () {}//Overwrite Finalize () methodprotected voidFinalize ()throwsThrowable {Super. Finalize (); System.out.println ("Obj [Date:" + This. GetTime () + "] is GC"); } PublicString toString () {return"Date:" + This. GetTime (); }}
In this class, the Java.util.Date class is extended and the Finalize () and ToString () methods are overridden.
creates a public class Referencetest, which is used to define a method Drainmemory (): Consumes a lot of memory, which causes the JVM to reclaim memory.
The Referencetest code is as follows:
PackageCom.skywang.java; Public classReferencetest {/**creates a new instance of Referencetest*/ Publicreferencetest () {}//consumes a lot of memory Public Static voiddrainmemory () {string[] array=Newstring[1024 * 10]; for(inti = 0; I < 1024 * 10; i++) { for(intj = ' a '; J <= ' Z '; J + +) {Array[i]+= (Char) J; } } }}
A static method, Drainmemory (), is defined in this class, which is designed to consume a lot of memory and cause the JVM to run garbage collection.
With the two public classes above, we can test when the JVM is garbage collected. There are 3 different scenarios to test:
Scenario 1: Clear Objects
Implementation Code :
Package Com.skywang.java; Public class Nogarbageretrieve { publicstaticvoid main (string[] args) { New mydate (); NULL ; }}
Operation result :
< no output >
Result Analysis : Although date is set to NULL, the MyDate Finalize () method is not run because the JVM does not perform garbage collection operations.
Scenario 2: Explicitly calling garbage collection
Implementation code :
PackageCom.skywang.java; Public classExplicitgarbageretrieve {/** * @paramargs*/ Public Static voidMain (string[] args) {//TODO auto-generated Method StubMyDate date =Newmydate (); Date=NULL; System.GC (); }}
Operation result :
obj [date:1372137067328] is GC
result analysis : called System.GC (), which enables the JVM to run garbage collection, the MyDate Finalize () method is run.
Scenario 3: Implicitly invoking garbage collection
Implementation code :
PackageCom.skywang.java; Public classImplicitgarbageretrieve {/** * @paramargs*/ Public Static voidMain (string[] args) {//TODO auto-generated Method StubMyDate date =Newmydate (); Date=NULL; Referencetest.drainmemory (); }}
Operation result :
obj [date:1372137171965] is GC
Result Analysis : Although the garbage collection Method System.GC () is not explicitly called, the JVM is triggered for garbage collection because of the memory-intensive methods that are running.
Summary: The garbage collection mechanism of the JVM, in case of memory adequacy, will not be garbage collected unless you explicitly call System.GC (), and garbage collection will run automatically if there is not enough memory
3. Java Reference classification
3.1 Strong References
Instance Code :
Package Com.skywang.java; Public class strongreferencetest { publicstaticvoid main (string[] args) { New mydate (); System.GC (); }}
Operation result :
< no output >
The result is that date is not reclaimed, even though garbage collection is explicitly called, but for date is a strong reference.
3.2 Soft References
Instance Code :
Package Com.skywang.java; Import java.lang.ref.SoftReference; Public class softreferencetest { publicstaticvoid main (string[] args) { New softreference (new mydate ()); Referencetest.drainmemory (); }}
Operation result :
< no output >
result description : Soft references are terminated when memory is low. When soft references are forbidden,
SoftReference ref = new SoftReference (new MyDate ());
Referencetest.drainmemory ();
Equivalent to
MyDate date = new MyDate ();
Run by JVM decision
If (JVM. Insufficient memory ()) {
date = null;
System.GC ();
}
3.3 Weak References
Example code :
Package Com.skywang.java; Import java.lang.ref.WeakReference; Public class weakreferencetest { publicstaticvoid main (string[] args) { New weakreference (new mydate ()); System.GC (); }}
Operation result :
obj [date:1372142034360] is GC
The result is that weak references are terminated when the JVM garbage collection runs.
WeakReference ref = new WeakReference (new MyDate ());
System.GC ();
Equivalent to:
MyDate date = new MyDate ();
Garbage collection
If (JVM. Insufficient memory ()) {
date = null;
System.GC ();
}
3.4 false References
Example code :
PackageCom.skywang.java;ImportJava.lang.ref.ReferenceQueue;Importjava.lang.ref.PhantomReference; Public classPhantomreferencetest { Public Static voidMain (string[] args) {referencequeue queue=NewReferencequeue (); Phantomreference ref=NewPhantomreference (Newmydate (), queue); System.GC (); }}
Operation result :
obj [date:1372142282558] is GC
The result shows that the false reference, after instantiation, is terminated.
Referencequeue queue = new Referencequeue ();
Phantomreference ref = new Phantomreference (new MyDate (), queue);
System.GC ();
Equivalent to:
MyDate date = new MyDate ();
date = null;
You can use the following table to summarize the above:
Level |
When is garbage collected? |
Use |
Survival time |
Strong references |
would never |
General state of the object |
Termination when JVM stops running |
Soft references |
When there is not enough memory |
Simple Object? Cache |
Terminate when memory is low |
Weak references |
At garbage collection time |
Object Cache |
Abort after GC run |
Virtual reference |
Unknown |
Unknown |
Unknown |
Click to download: Source Code
Reprinted from: http://www.cnblogs.com/skywang12345/p/3154474.html
Java References summary--strongreference, SoftReference, WeakReference, phantomreference