java basics: strong, weak, references, references and soft virtual reference (rpm) strong references to talk about Java object, soft references, weak references, phantom references are what

Source article:

  Java Basics - strong, weak, references, virtual references and soft references

  What to talk about the strong reference Java objects, soft references, weak references, phantom references, respectively


 

 

the whole frame

 

java provides a reference type 4, when garbage collection, each with its own characteristics.

Why are so many references to distinguish it, in fact, this is closely related to GC and Java.

A strong reference (the default mode support)

  • A reference to the object is assigned to a variable, the reference variable is a strong reference.
  • Strong references are our most common ordinary object reference, as long as there is a strong reference point to an object, the object will be able to show alive
  • When out of memory, jvm start garbage collection, strong references to the object, even if it will not appear OOM reclaim the object.
    Therefore, strong reference is the main cause of java memory leaks.
  • For an ordinary object, if no other references to the relationship, as long as more than the scope references or display of the references assigned to null, GC will recover the object.

Case

  public static void main(String[] args) {
        Obj Object = new new Object (); // this definition is a strong reference 
        Object obj = obj2; // is a strong reference 
        obj = null ;
        System.gc();
        // will not be garbage collected 
        System.out.println (obj2);
    }

Soft references (SoftReference)

  • Is a relatively soft references cited weakening strengthen a number of references, you need java.lang.SoftReference class to achieve.
  • For objects only soft references, the
    when the system memory is sufficient time, will not be recovered;
    when there is insufficient system memory will be recycled;

Case

/**
     * Jvm Configuration small memory, deliberately produce large objects, causing OOM,
     * Verify whether soft references before and after being recovered enough memory.
     * Parameters: -Xms: 5M -Xmx: 5M
     * @param args
     */
    public static void main(String[] args) {
        Obj Object = new new Object (); // this definition is a strong reference
         // soft references need to implement java.lang.SoftReference
         // now sf is a soft reference 
        SoftReference sf = new new SoftReference (obj);

        obj=null;

        System.out.println ( "soft enough memory referenced objects referenced by" + sf.get ());

        try {
            final byte[] bytes = new byte[8 * 1024 * 1024];
        } catch (Exception e) {
            e.printStackTrace ();
        }finally {
            System.out.println ( "not enough memory: Soft references are cited:" + sf.get ());
        }

    }

result:

Weak references

  • Weak references needed java.lang.WeakReference class to implement, it refers to the lifetime of softer than shorter.

* If an object is only referenced by weak references, as long as GC occurred, regardless of memory is not enough, we will recover the object.

  • ThreadLocal static inner classes ThreadLocalMap Entiry in the key is a virtual reference;

Case

public static void main(String[] args) {
        Object obj=new Object();
        WeakReference wrf=new WeakReference(obj);
        obj=null;
        System.out.println ( "GC does not occur before the" + wrf.get ());
        System.gc();
        System.out.println ( "adequate memory, occurs after GC" + wrf.get ());
    }

result:

Before java.lang.Object@2d363fb3 GC does not occur
Ample memory, null occurs after GC

You know weak references, then you can talk about WeakHashMap?

WeakHashMap key is "weak bonds" that is cited is a weak reference bond.

public static void main(String[] args) {
        WeakHashMap<String,Integer> map=new WeakHashMap<>();
        String key = new String("wekHashMap");
        map.put(key,1);
        key=null;
        System.gc();
        System.out.println(map);
    }

The results: map is empty.
Theoretically we just put a reference variable key becomes null, "wekHashMap" string should be in the Map key references ah, ah should not be GC recovery,
but because key is weak references, GC recovery when he ignored the quote, the recovered objects as garbage.

False quote

  • Virtual reference requires java. Langref.PhantomReference classes to implement.
  • As the name suggests, is non-existent, and several other references are different, virtual reference and does not determine the object's life cycle.
    If an object is only referenced virtual hold, and then it does not have any references, are likely to be garbage collected at any time.
  • It can be used alone or it can not access the object, and reference must reference the virtual queue (Reference queue) in combination.
  • The main role of the virtual reference is to track the object is garbage collected state. Merely provides an object is to ensure that after finalize, to do certain things mechanisms.
  • PhantomReference get method always returns null, and therefore can not access the referenced objects corresponding.
    It is about the use described object has entered a finalization stage, can be recycled, used to implement more flexible than finalization recovery operation mechanisms
    other words, the sole purpose of setting an imaginary reference associated, in this object is recovered when the collector receive a notification system or the subsequent addition of further processing;

ReferenceQueue reference queue

  • Before being recycled objects to be referenced queue save it. GC before the object is not placed in the queue, the object was placed in the queue after GC.
  • [The reference to changes in the queue thread by turning listeners] can take appropriate action when the object is recovered.
    Must be associated with a reference queue due to the sole purpose of virtual reference system is the ability to receive notification when this object is garbage collected, and thus create a virtual reference, but soft and weak references are not necessary.
    Here the so-called notified and actually turned thread or by listening to the changes in the reference queue to achieve.
  • There should also be emphasized that,
    for soft and weak references, when performing a first garbage collection, they will be soft or weak references cited references add objects to its associated queue and then finalize its function will be executed ( If no duplicate is not executed);
    whereas the imaginary reference, if the referenced object is not replication finalize method is the destruction of a first garbage collection after the class, references will add objects to the virtual reference queue,
    if a reference object replication finalize process is finished after performing a second garbage collection, only the virtual reference object to its associated reference queue
class User{
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println ( "GC I want to be done!" );
    }
}
 public static void main(String[] args) throws  Exception {
        User user=new User();
        ReferenceQueue<User> queue=new ReferenceQueue();
        PhantomReference prf=new PhantomReference(user,queue);

        // start a thread to monitor changes in the reference queue of 
        new new the Thread (() -> {
             for (;;) {
                 Final Reference <? The extends the User> U = queue.poll ();
                 IF ! (U = null ) {
                    System.out.println ( "objects have been added to the reference queue!" + U);
                }
            }
        }).start();

        User = null ;
         // until the queue is empty reference GC 
        System.out.println ( "prior to GC" + queue.poll ());
        
        System.gc();
        Thread.sleep ( 100 );
         // reference object into the queue until after the GC 
        System.out.println ( "first time after the GC" + queue.poll ());

        System.gc();
        Thread.sleep(100);
        System.out.println ( "second time after the GC" + queue.poll ());

    }

result:

GC before null
GC I want to be done!
After the first GC null
There are objects to be added to the reference queue up! java.lang.ref.PhantomReference@549763fd
After the second GC java.lang.ref.PhantomReference@5aaa6d82 

Scenarios

Soft references: SoftReference application scenarios

If you have an application that needs to read a large number of local images
each read images are read from the hard disk will affect the performance.
Loaded into memory all at once, it may cause memory overflow.
At this point, you can use soft references to solve the problem;
the mapping between references to the use of a HashMap save the image associated with the path and the response picture objects soft,
low memory, jvm will automatically reclaim the space occupied by these objects cached images can be avoided OOM.

Map<String,SoftReference<Bigmap>> imageCache=new HashMap<String,SoftReference<Bitmap>>();

 

 

the whole frame

 

java provides a reference type 4, when garbage collection, each with its own characteristics.

Why are so many references to distinguish it, in fact, this is closely related to GC and Java.

A strong reference (the default mode support)

  • A reference to the object is assigned to a variable, the reference variable is a strong reference.
  • Strong references are our most common ordinary object reference, as long as there is a strong reference point to an object, the object will be able to show alive
  • When out of memory, jvm start garbage collection, strong references to the object, even if it will not appear OOM reclaim the object.
    Therefore, strong reference is the main cause of java memory leaks.
  • For an ordinary object, if no other references to the relationship, as long as more than the scope references or display of the references assigned to null, GC will recover the object.

Case

  public static void main(String[] args) {
        Obj Object = new new Object (); // this definition is a strong reference 
        Object obj = obj2; // is a strong reference 
        obj = null ;
        System.gc();
        // will not be garbage collected 
        System.out.println (obj2);
    }

Soft references (SoftReference)

  • Is a relatively soft references cited weakening strengthen a number of references, you need java.lang.SoftReference class to achieve.
  • For objects only soft references, the
    when the system memory is sufficient time, will not be recovered;
    when there is insufficient system memory will be recycled;

Case

/**
     * Jvm Configuration small memory, deliberately produce large objects, causing OOM,
     * Verify whether soft references before and after being recovered enough memory.
     * Parameters: -Xms: 5M -Xmx: 5M
     * @param args
     */
    public static void main(String[] args) {
        Obj Object = new new Object (); // this definition is a strong reference
         // soft references need to implement java.lang.SoftReference
         // now sf is a soft reference 
        SoftReference sf = new new SoftReference (obj);

        obj=null;

        System.out.println ( "soft enough memory referenced objects referenced by" + sf.get ());

        try {
            final byte[] bytes = new byte[8 * 1024 * 1024];
        } catch (Exception e) {
            e.printStackTrace ();
        }finally {
            System.out.println ( "not enough memory: Soft references are cited:" + sf.get ());
        }

    }

result:

Weak references

  • Weak references needed java.lang.WeakReference class to implement, it refers to the lifetime of softer than shorter.

* If an object is only referenced by weak references, as long as GC occurred, regardless of memory is not enough, we will recover the object.

  • ThreadLocal static inner classes ThreadLocalMap Entiry in the key is a virtual reference;

Case

public static void main(String[] args) {
        Object obj=new Object();
        WeakReference wrf=new WeakReference(obj);
        obj=null;
        System.out.println ( "GC does not occur before the" + wrf.get ());
        System.gc();
        System.out.println ( "adequate memory, occurs after GC" + wrf.get ());
    }

result:

Before java.lang.Object@2d363fb3 GC does not occur
Ample memory, null occurs after GC

You know weak references, then you can talk about WeakHashMap?

WeakHashMap key is "weak bonds" that is cited is a weak reference bond.

public static void main(String[] args) {
        WeakHashMap<String,Integer> map=new WeakHashMap<>();
        String key = new String("wekHashMap");
        map.put(key,1);
        key=null;
        System.gc();
        System.out.println(map);
    }

The results: map is empty.
Theoretically we just put a reference variable key becomes null, "wekHashMap" string should be in the Map key references ah, ah should not be GC recovery,
but because key is weak references, GC recovery when he ignored the quote, the recovered objects as garbage.

False quote

  • Virtual reference requires java. Langref.PhantomReference classes to implement.
  • As the name suggests, is non-existent, and several other references are different, virtual reference and does not determine the object's life cycle.
    If an object is only referenced virtual hold, and then it does not have any references, are likely to be garbage collected at any time.
  • It can be used alone or it can not access the object, and reference must reference the virtual queue (Reference queue) in combination.
  • The main role of the virtual reference is to track the object is garbage collected state. Merely provides an object is to ensure that after finalize, to do certain things mechanisms.
  • PhantomReference get method always returns null, and therefore can not access the referenced objects corresponding.
    It is about the use described object has entered a finalization stage, can be recycled, used to implement more flexible than finalization recovery operation mechanisms
    other words, the sole purpose of setting an imaginary reference associated, in this object is recovered when the collector receive a notification system or the subsequent addition of further processing;

ReferenceQueue reference queue

  • Before being recycled objects to be referenced queue save it. GC before the object is not placed in the queue, the object was placed in the queue after GC.
  • [The reference to changes in the queue thread by turning listeners] can take appropriate action when the object is recovered.
    Must be associated with a reference queue due to the sole purpose of virtual reference system is the ability to receive notification when this object is garbage collected, and thus create a virtual reference, but soft and weak references are not necessary.
    Here the so-called notified and actually turned thread or by listening to the changes in the reference queue to achieve.
  • There should also be emphasized that,
    for soft and weak references, when performing a first garbage collection, they will be soft or weak references cited references add objects to its associated queue and then finalize its function will be executed ( If no duplicate is not executed);
    whereas the imaginary reference, if the referenced object is not replication finalize method is the destruction of a first garbage collection after the class, references will add objects to the virtual reference queue,
    if a reference object replication finalize process is finished after performing a second garbage collection, only the virtual reference object to its associated reference queue
class User{
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println ( "GC I want to be done!" );
    }
}
 public static void main(String[] args) throws  Exception {
        User user=new User();
        ReferenceQueue<User> queue=new ReferenceQueue();
        PhantomReference prf=new PhantomReference(user,queue);

        // start a thread to monitor changes in the reference queue of 
        new new the Thread (() -> {
             for (;;) {
                 Final Reference <? The extends the User> U = queue.poll ();
                 IF ! (U = null ) {
                    System.out.println ( "objects have been added to the reference queue!" + U);
                }
            }
        }).start();

        User = null ;
         // until the queue is empty reference GC 
        System.out.println ( "prior to GC" + queue.poll ());
        
        System.gc();
        Thread.sleep ( 100 );
         // reference object into the queue until after the GC 
        System.out.println ( "first time after the GC" + queue.poll ());

        System.gc();
        Thread.sleep(100);
        System.out.println ( "second time after the GC" + queue.poll ());

    }

result:

GC before null
GC I want to be done!
After the first GC null
There are objects to be added to the reference queue up! java.lang.ref.PhantomReference@549763fd
After the second GC java.lang.ref.PhantomReference@5aaa6d82 

Scenarios

Soft references: SoftReference application scenarios

If you have an application that needs to read a large number of local images
each read images are read from the hard disk will affect the performance.
Loaded into memory all at once, it may cause memory overflow.
At this point, you can use soft references to solve the problem;
the mapping between references to the use of a HashMap save the image associated with the path and the response picture objects soft,
low memory, jvm will automatically reclaim the space occupied by these objects cached images can be avoided OOM.

Map<String,SoftReference<Bigmap>> imageCache=new HashMap<String,SoftReference<Bitmap>>();

 

Guess you like

Origin www.cnblogs.com/myseries/p/11823930.html