Four ways to refer to Java

Source: Internet
Author: User

I. Reference to BASIC concepts

Starting with the JDK1.2 version, the object's references are divided into four levels, giving the program more flexibility in controlling the object's life cycle. These four levels are from high to low: strong references, soft references, weak references, virtual references.

1. Strong citation (Strongreference)

If an object has a strong reference, it is similar to essential necessities, and 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.


2. Soft Reference (SoftReference)

If an object has only soft references, it is similar to a living thing that can be used. If the memory space is sufficient, the garbage collector does not reclaim 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 garbage collected, the Java Virtual machine will add the soft reference to the reference queue associated with it.


3. Weak references (WeakReference)

If an object has only weak references, it is similar to a living thing that can be used. 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.


4. 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 garbage collected at any time, just as there are no references.

The only use of virtual references is when a trace reference is queued to referencequeue. It allows us to know exactly when an object is being removed from memory, and this feature can be used in some special requirements (for example, distributed Gc,xwork and Google-guice also use phantomreference to do some cleanup work).

Second, the Code test

 Public classReference { Public Static voidMain (string[] args) {Try{System.out.println ("Strong References");            Strongreference (); System.out.println ("=== === === ==="); System.out.println ("Soft Reference");            SoftReference (); System.out.println ("=== === === ==="); System.out.println ("Weak references");            WeakReference (); System.out.println ("=== === === ==="); System.out.println ("Virtual Reference");            Phantomreference (); System.out.println ("=== === === ==="); System.out.println ("Weakhashmap");            Weakhashmap (); System.out.println ("=== === === ==="); System.out.println ("Referencequeue");            Referencequeue (); System.out.println ("=== === === ==="); } Catch(Interruptedexception e) {}}/**strong references, default implementations of the JVM*/     Public Static voidStrongreference ()throwsinterruptedexception {Object obj=NewObject (); Object Strong=obj; Obj=NULL;        System.GC (); Thread.Sleep (1000);    System.out.println (strong); }    /*** SoftReference SoftReference in WeakReference are basically consistent, the biggest difference is that * SoftReference will keep the reference as long as possible until the JVM is out of memory (virtual Machine Guarantee) **/     Public Static voidSoftReference ()throwsinterruptedexception {Object obj=NewObject (); SoftReference<Object> sr =NewSoftreference<object>(obj); Obj=NULL;        System.GC (); Thread.Sleep (1000);    System.out.println (Sr.get ()); }    /*** WeakReference Weak reference (when the referenced object no longer has a strong reference within the JVM, weak reference will be automatically reclaimed after GC) **/     Public Static voidWeakReference ()throwsinterruptedexception {Object obj=NewObject (); WeakReference<Object> WR =NewWeakreference<object>(obj); Obj=NULL;        System.GC (); Thread.Sleep (1000);    System.out.println (Wr.get ()); }    /*** phantomreference Phantom Reference (Ghost Reference) differs greatly from WeakReference and SoftReference * because its get () method always returns null * */     Public Static voidPhantomreference ()throwsinterruptedexception {Object obj=NewObject (); Referencequeue<Object> RQ =NewReferencequeue<object>(); Phantomreference<Object> PR =NewPhantomreference<object>(obj, RQ);    System.out.println (Pr.get ()); }    /*** Using WeakReference as key, once there is no strong reference to key, Weakhashmap will automatically delete the relevant * entry after GC*/     Public Static voidWeakhashmap ()throwsinterruptedexception {Map<object, object> map =NewWeakhashmap<object, object>(); Object Key=NewObject (); Object value=NewObject ();        Map.put (key, value); Key=NULL;        System.GC (); Thread.Sleep (1000);        System.out.println (value);    System.out.println (Map.containsvalue (value)); }        /*** Referencequeue test method*/     Public Static voidReferencequeue ()throwsinterruptedexception {Object obj=NewObject (); Referencequeue<Object> RQ =NewReferencequeue<object>(); WeakReference<Object> PR =NewWeakreference<object>(obj, RQ); System.out.println (pr.isenqueued ());//notifies the program or garbage collector whether this reference object has been queued. System.out.println (Rq.poll ());//Poll This queue to see if there are available reference objects. obj =NULL;        System.GC ();    System.out.println (pr.isenqueued ()); }}

Four ways to refer to Java

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.