Four JAVA reference methods

Source: Internet
Author: User

Preface
Speaking of this last week's weekly meeting, the boss suddenly felt that he was not well remembered. Haha ~ Although this is the underlying layer in the project application, it will not be developed, and it will not be used online, but as a basic java knowledge, let's review the four reference methods in java: strong reference, soft reference, weak reference, and virtual reference.
1. Basic concepts of reference
1.1 strong references
When we use the new keyword to create an Object, the created object is strongly referenced. For example, Object = new Object () is a strongly referenced object, if an object has a strong reference. The garbage collector will not recycle objects with strong references. For example, if the jvm memory is insufficient and there are strongly referenced objects, the virtual machine would rather report an exception in insufficient memory space to terminate the program, nor will it rely on the garbage collector to recycle the object to solve the memory.
1.2 soft references
If an object has soft references and the memory space is sufficient, the garbage collector will not recycle it. If the memory space is insufficient, the object will be recycled. Of course, this object can still be called by the program before it is recycled.
1.3 weak references
If an object has only weak references, the garbage collector will immediately be recycled and the corresponding memory will be released as long as the thread detects the object in its memory space. The lifecycle of a soft reference is much shorter than that of a soft reference. However, if the garbage collector is a thread with a low priority, it may not release soft Reference Memory soon.
1.4. Virtual references
If an object only has a virtual reference, it will be recycled by jvm as garbage at any time, just like there is no reference.
2. jdk reference level
Jdk1.2 did not have these concepts before. In jdk1.2 and later versions, four levels of reference were introduced in sequence: strong reference, soft reference, weak reference, and virtual reference.
In jdk, the java. lang. ref. Reference class refers to the abstract base class referenced by java. reference defines the operations on referenced objects. Of course, this class is used with the garbage collector.

3. Use of reference and queue
Strong references are generally not used together with the queue, Which is filtered out.
Soft references can be used together with a reference queue. Generally, soft references can be used to implement memory-sensitive high-speed cache. If the referenced objects of soft references are garbage collected, the Java Virtual Machine will import the reference to the associated reference queue.
Weak references are used together with the queue. If the objects referenced by the weak references are recycled, the Java Virtual Machine will add the weak references to the associated queue;
Virtual references: When the Java Virtual Machine recycles the virtual quotes, the virtual references are placed in the associated reference queue. The program can determine whether the referenced object has been referenced in the reference queue to check whether the referenced object is to be recycled. If the program finds that a virtual reference has been added to the reference queue, it can take some logical processing before the referenced object memory.

4. jdk reference implementation class
Indicates soft reference class: java. lang. ref. SoftReference
Indicates the weak reference class: java. lang. ref. WeakReference
Indicates the Virtual Reference class: java. lang. ref. PhantomReference
They also inherited: java. lang. ref. Reference
Reference queue: java. lang. ref. ReferenceQueue. This reference queue can be used in combination with three reference types to track the activity of java Virtual Machine to recycle referenced objects.
5. example reference

How to implement a soft reference?

/*** Implement a soft reference */public static void testSoftReference () {// create a strongly referenced TestString str = new String ("Test "); // create a reference queue ReferenceQueue
 
  
Rq = new ReferenceQueue
  
   
(); // Implement a soft reference. Place str and rq of the strong reference type into the soft reference implementation. SoftReference
   
    
Srf = new SoftReference
    
     
(Str, rq); // obtain the memory space Test value System created in the strong reference using the soft reference get method. out. println (srf. get (); // The gc program execution now has a lot of jvm memory space, so gc will not recycle the str object System. gc (); // so running get will print the System of Test. out. println (srf. get ());}
    
   
  
 
After executing this soft reference, what will happen to the jvm stack area?

VcTatOa/1bzk1tDIpaGjPGJyPgo8aW1nIHNyYz0 = "http://www.2cto.com/uploadfile/Collfiles/20140316/20140316100002208.jpg" alt = "\">
How to implement a weak reference?

/*** Implement a weak reference */public static void testWeakReference () {String str = new String ("Test"); ReferenceQueue
 
  
Rq = new ReferenceQueue
  
   
(); // Implement a weak reference. Put str and rq of the strong reference type into the WeakReference implementation.
   
    
Wrf = new WeakReference
    
     
(Str, rq); // returns a null value to str. Then, the reference str = null of the Test object is obtained through the get () method of weak WeakReference; // The program executes gc in multiple ways to increase the gc execution thread frequency to recycle objects. System. gc (); // if it has not been recycled, run wrf in step 1. the get () method returns the reference of the Test object and causes this object to be referenced by str1. // Then, If you execute the rq. poll () method on the row, null is returned because no reference is provided in the reference queue. String str1 = wrf. get (); System. out. println (str1); // The poll () method of ReferenceQueue is used to return a reference in the queue. If not, null is returned. Reference
     
      
Ref = (Reference
      
        ) Rq. poll (); System. out. println ("weak reference disappears" + ref); if (ref! = Null) {System. out. println (ref. get ());}}
      
     
    
   
  
 

6. Integrated instances

/*** Create a reference Object ref * @ author TianYou */public class RefObject {private static final int size = 80000; // create an Object array, this will occupy a lot of memory space. Approximately KB of memory is expected to be occupied. private Object [] object = new Object [size]; private String refId; public RefObject (String id) {this. refId = id;} public String RefIdToString () {return refId;} public void findName () {System. out. println ("findName =" + refId) ;}} test class package reference; import java. lang. ref. phantomReference; import java. lang. ref. reference; import java. lang. ref. referenceQueue; import java. lang. ref. softReference; import java. lang. ref. weakReference; import java. util. hashSet; import java. util. set;/*** test reference * @ author TianYou */public class TestReference {// create a reference queue private static ReferenceQueue
 
  
Rq = new ReferenceQueue
  
   
(); Private static int size = 10;/*** verification queue */public static void checkQueue () {Reference
   Ref = rq. poll (); if (null! = Ref) System. out. println ("In queue:" + ref + ":" + ref. get ();}/*** create 10 RefObject Objects \ and 10 soft references */public static void testSoftReference () {System. out. println ("-------- execute soft reference start -------"); Set
   
    
> Sa = new HashSet
    
     
> (); For (int I = 0; I <size; I ++) {SoftReference
     
      
Ref = new SoftReference
      
        (New RefObject ("SoftReference" + I), rq); System. out. println ("Just created:" + ref. get (); sa. add (ref);} System. gc (); checkQueue (); System. out. println ("-------- execute soft reference end -------");}/*** create 10 Grocery objects and 10 weak references */public static void testWeakReference () {System. out. println ("-------- starting from executing weak references -------"); Set
       
         > Wa = new HashSet
        
          > (); For (int I = 0; I <size; I ++) {WeakReference
         
           Ref = new WeakReference
          
            (New RefObject ("WeakReference" + I), rq); System. out. println ("Just created:" + ref. get (); wa. add (ref);} System. gc (); checkQueue (); System. out. println ("-------- execution weak end -------");}/*** create 10 Grocery objects and 10 virtual references */public static void testPhantomReference () {System. out. println ("-------- starting from executing the Virtual Reference -------"); Set
           
             > Pa = new HashSet
            
              > (); For (int I = 0; I <size; I ++) {PhantomReference
             
               Ref = new PhantomReference
              
                (New RefObject ("PhantomReference" + I), rq); System. out. println ("Just created:" + ref. get (); pa. add (ref);} System. gc (); checkQueue (); System. out. println ("-------- execution weak end -------");} public static void main (String args []) {testSoftReference (); testWeakReference (); testPhantomReference ();}}
              
             
            
           
          
         
        
       
      
     
    
   
  
 
On the Comprehensive instance, we can see that the three references are created 10 times in sequence and contain a refobject object. From the printed results, we can clearly see that the virtual references are basically the same as virtual ones, the referenced objects are recycled by the garbage collector at any time. Objects with weak references have a longer life cycle. However, when the garbage collector performs a return operation, it is still possible to be recycled by the garbage collector, and soft reference is still applied for a long life cycle. However, when the VM memory is insufficient, it will still be recycled. Therefore, these reference methods are not suitable for online use, otherwise, it is difficult to detect the results when it is very likely to applaud.
7. Weak referenced WeakHashMap
The weak referenced jar path is java. util. WeakHashMap. It is a map of hash tables implemented by weak references as keys. When a key in the weakHashMap table is abnormal, the abnormal key is automatically removed. If you hold a strongly referenced key, it will always exist. It also supports null key and null value. More precisely, for a given key, the existence of its ing does not prevent the garbage collector from recycling the key, which enables the key to be terminated and the key to be terminated, then, the garbage collector recycles the data. When a key is recycled, its entries are also effectively removed from the ing. Therefore, the behavior of this class is different from that of other Map implementations.
Next, let's take a look at the instance.
Create a key object

Public class Key {String id; public Key (String id) {this. id = id;} public String toString () {return id;} public int hashCode () {return id. hashCode ();} public boolean equals (Object r) {return (r instanceof Key) & id. equals (Key) r ). id);} public void finalize () {System. out. println ("Finalizing Key" + id) ;}} creates a value object public class Value {String id; public Value (String id) {this. id = id;} public String toString () {return id;} public void finalize () {System. out. println ("Finalizing Value" + id) ;}} test object import java. util. weakHashMap; public class MapCache {public static void main (String [] args) throws Exception {int size = 10000; Key [] keys = new Key [size]; WeakHashMap
 
  
Whm = new WeakHashMap
  
   
(); For (int I = 0; I <size; I ++) {Key k = new Key (Integer. toString (I); Value v = new Value (Integer. toString (I); if (I % 5 = 0) keys [I] = k; // make the Key object hold a strongly referenced whm. put (k, v); // make the Key object hold weak references} // urge the Garbage Collector to work System. gc (); // give the CPU to the garbage collector Thread. sleep (8000) ;}} the running result shows that 5 of the objects hold strong references and are retained.
  
 

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.