Reference types in Java

Source: Internet
Author: User
Tags whm

What types of references are in Java?

In addition to the 8 basic data types (which do not include void), others are reference types.

Maybe the interviewer is asking the above, but if you can add it, it will be a good opportunity to show!

Java There are 4 types of references in: strong, soft, weak, virtual! This classification is related to GC, if you have some understanding of the GC, you can continue to talk about, if you do not understand the GC, it is advisable to stop.

1. Strong, soft, weak, and virtual references to objects

In previous versions of JDK 1.2, if an object was not referenced by any variable, the program could no longer use the object. That is, only the object is in the accessible (reachable) state before the program can use it. Starting with JDK version 1.2, the reference to the object is divided into 4 levels, giving the program more flexibility in controlling the object's life cycle. These 4 levels are high to low in order: Strong references, soft references, weak references, and virtual references.

1 strong reference (Strongreference)
    virtual machine would rather throw a outofmemoryerror error that would cause the program to terminate abnormally, It is also not easy to recycle a strongly referenced object to resolve an out-of-memory problem.

2 soft reference (SoftReference)
    If an object has only soft references, enough memory is available, the garbage collector does not recycle it, and if the memory space is low, 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 are available for memory-sensitive caching
    soft references can be used in conjunction with a reference queue (Referencequeue), if the object referenced by the soft reference is reclaimed by the garbage collector, The Java Virtual machine will add this soft reference to the reference queue associated with it.

3) /span> weak reference (WeakReference)
    The difference between weak and soft references is that weakly referenced objects have 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.
    Weak references 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 will add the weak reference to the reference queue associated with it.

String str = new string ("Hello"); --1--referencequeue<string> RQ = new referencequeue<string> (); --2--weakreference<string> wf = new weakreference<string> (str, RQ); --3--Str=null; --4--a strong reference to the "Hello" object, String str1=wf.get (); --5--if the "Hello" object is not recycled, str1 references the "Hello" object//If the "Hello" object is not reclaimed, rq.poll () returns null reference<? Extends string> ref=rq.poll (); --6--


         arrows with solid lines represent strong references, and arrows with dashed lines indicate weak references. As you can see, at this point"Hello"object isStra strong reference, and isWeakReferenceobject is weakly referenced, so"Hello"objects are not garbage collected.
in the following program code, refer to the"Hello"object thatStrthe variable is placedNULL, and then go throughWeakReferenceof weakly referencedget ()method to obtain"Hello"reference to the object:

 when the above line of ④ is executed, the in-memory reference is related to the object11-11as shown, this when"Hello"An object has only a weak reference, so it may be garbage collected. If it has not yet been garbage collected, then the next step in line ⑤Wf.get ()method will return"Hello"object, and causes the object to bestr1strong references. And then in line ⑥.Rq.poll ()method will returnNULL, because at this point the reference queue does not have any references. Referencequeueof thepoll ()method is used to return a reference in the queue, or if none is returnedNULL.

         in the following program code, after the execution of line ④,"Hello"objects have only weak references. The next two callsSystem.GC ()method, urging the garbage collector to work, thereby improving"Hello"the possibility of objects being recycled. If"Hello"object is recycled, thenWeakReferencethe reference to the object is added to theReferencequeuein which NextWf.get ()method returnsNULL, andRq.poll ()method returnsWeakReferencethe reference to the object. Figure11-12shows the memory after line ⑧ is executed The relationship to the object is referenced in the  


String str = new string ("Hello"); ①referencequeue<string> RQ = new referencequeue<string> (); ②weakreference<string> wf = new weakreference<string> (str, RQ); ③str=null; ④//two times to urge the garbage collector to work, increasing the likelihood of "hello" objects being recycled System.GC (); ⑤SYSTEM.GC (); ⑥string Str1=wf.get (); ⑦ If "Hello" object is recycled, str1 is nullreference<? Extends string> ref=rq.poll (); ⑧


in the following routines11-15of theReferencesclass, you create aTena soft reference,Tena weak reference andTenA virtual reference, each of which references aGroceryobject. From the program transport when a row is printed, it can be seen that the virtual reference is fake, the object it refers to can be garbage collected at any time, an object with a weak reference has a slightly longer life cycle, and when the garbage collector performs a recycling operation, it can can be garbage collected, objects with soft references have a longer life cycle, butJava

Import java.lang.ref.*;import java.util.*;class grocery{private static final int  size = 10000;//attribute D makes each grocery object occupy more memory, with about 80K        private  double[] d = new double[SIZE];         Private string id;       public grocery (String id)  { this.id = id; }       public String  ToString ()  { return id; }       public void  Finalize ()  {                 system.out.println ("finalizing "  + id);        }}public  class References {       private static  Referencequeue<grocery> rQ = new referencequeue<grocery> ();       public  Static void checkqueue ()  {                 reference<? extends grocery> inq = rq.poll ();                  // Remove a reference                 if from the queue ( Inq != null)                  system.out.println ("in queue: " +inq+ " : " +inq.get ());        }       public static void main (String[]  args)  {       final int size=10;         //Create 10A grocery object and 10 soft references        set<softreference<grocery>> sa  = new HashSet<SoftReference<Grocery>> ();        for (int i = 0; i < size; i++)  {                 SoftReference<Grocery> ref=                 new SoftReference< Grocery> (New grocery ("soft "  + i), &NBSP;RQ);                 system.out.println ("just created: "  + Ref.get ());                 Sa.add (ref);        }       system.gc ();    &nbsP;   checkqueue ();        //Create 10 grocery objects and 10 weak references         Set<WeakReference<Grocery>> wa = new  Hashset<weakreference<grocery>> ();        for (int i =  0; i < size; i++)  {                 WeakReference<Grocery> ref=                 new WeakReference<Grocery> (New  grocery ("weak "  + i), &NBSP;RQ);                 system.out.println ("just created: "  +ref.get ());                 wa.add (ref);       &nBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.GC ();        Checkqueue ();        //Create 10 Grocery objects and 10 virtual references         Set<PhantomReference<Grocery>> pa = new      Hashset<phantomreference<grocery>> ();        for (int i  = 0; i < size; i++)  {                 PhantomReference<Grocery>ref =                  new phantomreference <Grocery> (New grocery ("phantom "  + i), &NBSP;RQ);                 system.out.println ("Just created: "  +ref.get ()); &NBSP;&NBSP;&NBsp;             pa.add (ref);   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.GC ();        checkqueue ();}}


There is a special type of map in the Java collection: Weakhashmap, where a weak reference to a key object is stored in this map, and when a key object is garbage collected, a reference to the corresponding value object is removed from the map. Weakhashmap can save storage space and can be used to cache data that is not required to exist. For general usage of the Map interface, refer to section 15.4 (map) of chapter 15th of this book.

the Main () method of the MapCache class of the following routine 11-16 creates a Weakhashmap object that holds a weak reference to a set of key objects, and the main () method creates an array object. It holds a strong reference to some key objects.

Routine 11-16 mapcache.javaimport java.util.*;import java.lang.ref.*; 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);}} 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);} Public class mapcache {public static void main (String[] args)  throws  exception{int size = 1000;//  or get size if (args.length > 0) Size = integer.parseint (Args[0]) from the command line; key[] keys = new key[size]; //Strong reference weakhashmap<key,value> whm = for storing key objects  new WeakHashMap<Key,Value> (); for (int i = 0; i < size; i + +)  {key k = new key (integer.tostring (i)); Value v = new value (integer.tostring (i)); if (i % 3 == 0)  keys[i]  = k; //causes the Key object to hold a strong reference  whm.put (K,&NBSP;V);  //The key object holds a weak reference}//urges the garbage collector to work System.GC ();  // Give the CPU to the garbage collector thread Thread.Sleep (8000);}} /* Some of the printed results for the above program are as follows: finalizing key 998finalizing key 997finalizing key 995finalizing  Key 994Finalizing Key 992Finalizing Key 991Finalizing Key  989finalizing key 988finalizing key 986finalizing key 985finalizing key  983*/


as can be seen from the print results, when executing System.GC () method, the garbage collector only reclaims Key objects that only hold weak references . the ID can be strongly referenced by a Key object of 3 integers and therefore will not be recycled.

Thanks to the original author:

Original link


Reference types in Java

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.