[Reprinted] the basis of Java 7, reprinted java Basics
Address: http://blog.csdn.net/mazhimazh/article/details/19752475
1. StrongReference)
Strong references are the most common references. If an object has a strong reference, the garbage collector will never recycle it. As follows:
Object o = new Object (); // strongly referenced
When the memory space is insufficient, the Java Virtual Machine would rather throw an OutOfMemoryError to terminate the program abnormally, and does not recycle strongly referenced objects at will to solve the problem of insufficient memory. When not in use, use the following method to weaken the reference:
O = null; // helps the Garbage Collector recycle this object
If o is explicitly set to null or exceeds the lifecycle of an object, gc considers that the object does not have a reference, and the object can be recycled. The specific time to collect depends on the gc algorithm.
Example:
Public void test () {Object o = new Object (); // omit other operations}
There is a strong reference inside a method. This reference is stored in the stack, and the actual reference content (Object) is saved in the heap. After the method is run, it exits from the method stack. If the reference content does not exist, the Object will be recycled.
However, if this o is a global variable, You need to assign a null value when this object is not used, because the strong reference will not be garbage collection.
Strong reference is very important in practice. For example, the Implementation source code of ArrayList:
private transient Object[] elementData;public void clear() { modCount++; // Let gc do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0;}
The ArrayList class defines a private variable elementData array. when calling the method to clear the array, you can see that the value of each array is null. Unlike elementData = null, strong references still exist, avoiding re-memory allocation when you call add () or other methods to add elements. The method for releasing memory in the clear () method is particularly applicable to the reference type stored in the array, so that the memory can be released in time.
2. Soft reference)
If an object only has soft references, the memory space is sufficient and the garbage collector will not recycle it. If the memory space is insufficient, the memory of these objects will be recycled. The object can be used by programs as long as the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive high-speed cache.
String str = new String ("abc"); // strong reference SoftReference <String> softRef = new SoftReference <String> (str); // soft reference
When the memory is insufficient, it is equivalent:
If (JVM. memory insufficient () {str = null; // convert to soft reference System. gc (); // recycle Garbage Collector}
It is used for important applications, such as the back button of the browser. When you press the back button, will the webpage content displayed when the back button be requested again or retrieved from the cache? This depends on the specific implementation strategy.
(1) If the content of a Web page is recycled at the end of browsing, you need to re-build it when you view the previously viewed page in the background.
(2) If you store browsed web pages in the memory, it will cause a lot of memory waste and even cause memory overflow.
In this case, you can use soft references.
Browser prev = new Browser (); // obtain the page to browse SoftReference sr = new SoftReference (prev); // After browsing, the soft reference if (sr. get ()! = Null) {rev = (Browser) sr. get (); // It has not been recycled by the recycler and can be directly obtained} else {prev = new Browser (); // due to memory shortage, therefore, sr = new SoftReference (prev) is reclaimed for soft referenced objects; // re-build}
In this way, the actual problem is solved.
Soft references can be used together with a ReferenceQueue. If the referenced objects are recycled by the garbage collector, the Java virtual machine adds this soft reference to the reference queue associated with it.
3. WeakReference)
The difference between weak references and soft references is that only objects with weak references have a shorter life cycle. When the Garbage Collector thread scans the memory area under its jurisdiction, its memory will be recycled no matter whether the current memory space is sufficient or not. However, since the garbage collector is a thread with a low priority, it may not soon find objects with weak references.
String str=new String("abc"); WeakReference<String> abcWeakRef = new WeakReference<String>(str);str=null;
It is equivalent:
str = null;System.gc();
If this object is used occasionally and you want to obtain it at any time, but do not want to affect the garbage collection of this object, you should use Weak Reference to remember this object.
The following code changes str to a strong reference again:
String abc = abcWeakRef.get();
Weak references can be used together with a ReferenceQueue, the Java virtual machine adds this weak reference to the reference queue associated with it.
When you want to reference an object, but this object has its own lifecycle, you do not want to intervene in the lifecycle of this object, at this time you are using weak references.
This reference will not have any additional impact on the object's garbage collection judgment.
Public class ReferenceTest {private static ReferenceQueue <VeryBig> rq = new ReferenceQueue <VeryBig> (); public static void checkQueue () {Reference <? Extends VeryBig> ref = null; while (ref = rq. poll ())! = Null) {if (ref! = Null) {System. out. println ("In queue:" + (VeryBigWeakReference) (ref )). id) ;}} public static void main (String args []) {int size = 3; vertex list <WeakReference <VeryBig> weakList = new vertex list <WeakReference <VeryBig> (); for (int I = 0; I <size; I ++) {weakList. add (new VeryBigWeakReference (new VeryBig ("Weak" + I), rq); System. out. println ("Just created weak:" + weakList. getLast ();} System. gc (); try {// take a few minutes to run the preceding garbage collection Thread. currentThread (). sleep (6000);} catch (InterruptedException e) {e. printStackTrace () ;}checkqueue () ;}} class VeryBig {public String id; // space occupied, so that the thread can recycle byte [] B = new byte [2*1024]; public VeryBig (String id) {this. id = id;} protected void finalize () {System. out. println ("Finalizing VeryBig" + id) ;}} class VeryBigWeakReference extends WeakReference <VeryBig> {public String id; public VeryBigWeakReference (VeryBig big, ReferenceQueue <VeryBig> rq) {super (big, rq); this. id = big. id;} protected void finalize () {System. out. println ("Finalizing VeryBigWeakReference" + id );}}
The final output result is:
Just created weak: com.javabase.reference.VeryBigWeakReference@1641c0Just created weak: com.javabase.reference.VeryBigWeakReference@136ab79Just created weak: com.javabase.reference.VeryBigWeakReference@33c1aaFinalizing VeryBig Weak 2Finalizing VeryBig Weak 1Finalizing VeryBig Weak 0In queue: Weak 1In queue: Weak 2In queue: Weak 0
4. PhantomReference)
As the name implies, "virtual references" are just the same as virtual ones, which are different from other types of references. Virtual references do not determine the object lifecycle. If an object only holds a virtual reference, it is the same as no reference and may be recycled by the garbage collector at any time.
Virtual references are used to track the activity of objects recycled by the garbage collector. A difference between virtual and soft references and weak references is that virtual references must be used together with the reference Queue (ReferenceQueue. When the garbage collector is preparing to recycle an object, if it finds that it has a virtual reference, it will add this virtual reference to the reference queue associated with it before it recycles the object's memory.
5. Summary
The reference levels of Java4 are as follows:
Strong reference> soft reference> weak reference> Virtual Reference
The figure shows the differences between them during garbage collection:
When the Garbage Collector recycles objects, some objects are recycled, and some objects are not recycled. The garbage collector will mark the surviving objects from the root Object, and then recycle some inaccessible objects and some referenced objects. If you are not familiar with this, you can refer to the following articles:
Portal: Java memory management http://blog.csdn.net/mazhimazh/article/category/1907599
Use the following table to describe:
References:
1. http://www.cnblogs.com/skywang12345/p/3154474.html
2, http://blog.csdn.net/lifetragedy? Viewmode = contents