Comparison of four reference types in Java

 

1. The concept of reference

Refer to this concept is the JAVA virtual machine and garbage collection related to different reference different types correspond garbage collection policy or timing.
Garbage collection is probably one of the more difficult we find it difficult to understand the concept, because it does not always solve the problem without missing the Java Runtime Environment heap management.
Garbage collection is the general idea: When the Java Virtual Machine that memory is not enough time, will trigger garbage collection (GC), remove unwanted objects and release memory. But how to determine whether an object is garbage it? One method is to calculate the number of references pointing to the object, if the reference number is zero, then the object is to refuse (Thread object is an exception), otherwise there is useful, can not be recycled. However, this reference counting algorithm not solve the problem of circular references, now JAVA virtual machine using a reachability analysis algorithm . Common situation is: an object is not directly referenced from the root, but an object is referenced by other objects, even simultaneously several objects referenced, thereby constituting a root of the tree is a top set, when an object unreachable (that is, when the object can not be obtained by reference to the object), this object and other objects referenced by that object will be treated as junk, this memory is likely to be followed by recovery JVM.

2. four kinds of reference types

Java provides a reference to the four levels, namely strong reference (FinalReference), soft references
(SoftReference), weak references (WeakReference), virtual reference (PhantomReference) four levels. At this level, only four strong reference category is visible within the package, the other three reference types are public, can be used directly in the application, the garbage collector will attempt to recover the object only weak references.
■ strong reference (Strong Reference): In a thread, without direct reference to the object that can be used, strong references will not be cleaned JVM. We usually declare variables used strong reference, more than 99% are common system strong references, for example, String s = "Hello World" .
■ Soft references (WeakReference): reference affirmed by a soft, JVM throws before OOM, clean up all the soft reference objects. When the garbage collector at some point decided to target up to the recovery of the soft, soft references will clean up, and the optional reference to a stored reference queue (ReferenceQueue).
■ weak reference (SoftReference): affirmed by a weak reference. Similarly weak references, but the opportunity to try to make the Java Virtual soft references survival time of some of the long, was forced to clean up.
■ virtual reference (PhantomReference): affirmed through a virtual reference. Only used to clean up the problem of processing resources, a more flexible mechanism than finalize Object inside. get method returns will always be null, Java Virtual Machine is not responsible for cleaning up the virtual reference, but it will put a virtual reference reference queue inside.

3. A strong reference (Strong Reference)

Java references, a bit like a pointer in C ++. , You can operate on objects in the heap by reference. In Java programs, the most common reference type is strong references, it is also the default reference type.
When creating a new object using the new operator in the Java language, and assign it to a variable, the variable will become a strong reference point to the object. The object is to determine whether a viable standard for the presence or absence of references to the object.
In one function, for example: StringBuffer str = new StringBuffer ( " Hello World"); Assuming that the function code is running in the body, then the local variable str will be allocated on the stack, and the object StringBuffer instance, is allocated on the heap . Examples of local variables StringBuffer str point where the stack space, which can be operated by str instance, it is StringBuffer str reference. At this time, if an assignment operation: StringBuffer str1 = str; then, str pointed objects will also be pointed str1, while storage space will be allocated in the local stack variables str1 space. At this time, "" Hello World "string objects have a two references, two references that point to an object at the same time. The reference to the" == "Operating with only the heap address space pointed to two operands It is the same, that is, whether two references point to the same object.

Strong reference has the following characteristics:
(1) strong references can be accessed by the target directly.
(2) strong reference object pointed at all times the system will not be recovered. Out Of Memory JVM would rather throw an exception would not recover strong reference object points.
(3) strong references may cause a memory leak.

There is a strong reference prevents an object is recovered. After traversing the garbage collector object reference and mark, if the object is a strong reference reachable, then this object is not a candidate for garbage collection. When the memory space is insufficient, Java Virtual Machine would rather throw OutOfMemoryError errors, abnormal termination of the program, it will not recover by random objects that have strong references to solve the problem of insufficient memory. When programmers write code, sometimes in order to prevent a memory leak, it is necessary to refer explicitly to the nulling (Object o = null). For example: In the ArrayList remove (int index), the last element forming empty.
snippet "public E remove (int index) " method

 elementData[--size] = null; // clear to let GC do its work

When implementing a caching system, if all use strong references, then you need to own some references to the manual of Clear off (a reference set to Null), otherwise it will sooner or later be thrown Out Of Memory error. The only reason caching system into soft or weak references cited is that the things cited Clear handed over to Java garbage collector to handle, Cache program yourself out of it.
Generally speaking, the application of internal memory leak there are two cases. One is the presence of a virtual machine program memory area can not be used, another case is the object of a lot of long survival time in the presence of the program.

4. Soft references (WeakReference)

Soft references are strong references cited in addition to outside the strongest type, we can quote by java.lang.ref.SoftReference soft. Holds a soft reference objects, it will not be soon recovered JVM, JVM will use to determine when to recover according to the current heap. When approaching the heap usage threshold, only to recover the object soft references. As long as there is enough memory, soft references will probably survive quite a long time in memory. Therefore, as one put it, the soft references can be used to implement memory-sensitive Cache. The garbage collector will ensure that before throwing OOM error recovery out all soft references objects reachable. By soft references, the garbage collector can release the soft references memory space up to the target share of low memory. After the program have to do is to ensure that up to soft reference object is garbage collected, the program can work.
Soft reference is characterized by its soft to hold an instance of a Java object reference, the soft references exist without prejudice to the recovery of the garbage collection thread Java objects. In other words, once the soft references save for a soft Java object reference in Java garbage thread before this object is reclaimed soft references get class provided () method returns a Java object of strong references. In addition, once the garbage recycling thread Java objects, get () method will return null.
Sample code:

import org.junit.Assert;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;

public class MyObject {
    public static ReferenceQueue<MyObject> softQueue;

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        Reference<MyObject> obj = null;
        Assert.assertNotNull(softQueue);
        obj = (Reference<MyObject>) softQueue.remove();
        System.out.println(obj);
        if (obj != null)
            System.out.println("Object for SoftReference is" + obj.get());
        System.out.println("MyObject finalize called ");//
    }

    @Override
    public String toString() {
        return "I am MyObject";
    }

    public static void main(String[] args) {
        MyObject obj = new MyObject();
        softQueue = new ReferenceQueue<>();
        SoftReference<MyObject> softRef = new SoftReference<>(obj, softQueue);
        System.out.println(obj);
        obj = null;
        System.gc();
        System.out.println(obj);
        System.out.println("After GC:Soft get=" + softRef.get());
        System.out.println ( "allocated chunk of memory" );
         byte [] bytes = new new  byte [1000 * 1024 * 925]; // allocate a large memory, forcing the GC 
        System.out.println ( "the After new new byte [] : Soft the Get = "+ softRef.get ());
        System.out.println(obj);
    }
}

 

As a Java object, soft references objects in addition to a general reference to the special nature of saving soft outside, also has a Java object. So, when the soft reference object is recovered, although the soft reference object get () method returns null, but this is no longer the object has a value of existence, the need for a proper clearance mechanisms, to avoid memory brought a large number of soft-referenced objects leakage. In java.lang.ref package also provides ReferenceQueue. If when creating the soft reference object, using a ReferenceQueue object as a parameter to the constructor soft references.

ReferenceQueue softQueue = new ReferenceQueue<>();
 SoftReference<MyObject> softRef = new SoftReference<>(obj, softQueue);

 

So when this SoftReference soft references held by the obj recycled garbage collector at the same time, softRef the strong references Soft references are included ReferenceQueue. In other words, the object is stored in ReferenceQueue Reference object, but has lost its soft reference objects Reference objects.
ReferenceQueue is a queue, which has the basic characteristics of the general queue, we can call the poll ReferenceQueue () method to check whether there is non-mandatory and that concern may be recovered. If the queue is empty, it returns a null, otherwise the method returns to the front of a queue Reference object. Using this method, we can examine the object which SoftReference soft references has been recovered. So we can put these objects lose SoftReference soft reference objects removed. Commonly used methods such as SoftReference ref = null; while (! (Ref = (EmployeeRef) q.poll ()) = null) {// Clear ref}.

The weak reference (the SoftReference)

1) weak reference is a reference weaker than the soft reference type (regardless of whether the system is sufficient heap space, the objects will be recovered), the use of weak references, you can maintain a reference to the referent, but will not prevent it from being garbage collected . When the garbage collector heap of track time, if the reference is only a weak reference to an object, then the referent becomes a candidate for garbage collection, just as there is no remaining references, and all of the remaining weak references are cleared. Weak references are set at construction, until they are cleared, it can get its value, if the weak reference has been cleared, whether it is garbage collected, or someone calls the clear () method, which returns null. Thus, prior to using a weak reference object must check returns a non-null value.
2) Because the garbage collector thread is usually very low priority, and therefore does not necessarily quickly find objects holds weak references. In this case, there may be a weak reference object longer. Once a weak reference object is garbage collected, it will be added to a queue registration reference. Examples of the above-described type only needs to change the object to weakReference, see once obj is set to null, GC recovered immediately if the type instance.
Weak references, soft references are very suitable to hold the cached data for those dispensable. If you do this, when there is insufficient system memory, the cache data will be recovered, it will not cause a memory overflow. When sufficient memory resources, the cache data and can exist for a long time, and thus play a role in accelerating system.
3) the important role of weak references is time to solve the problem of long survival target. In the program, the actual survival of an object and it should be the same as the logic of survival. Logically, one object should follow a method call completes it is no longer needed, it can be garbage collected. However, if there are other strong references exist, the actual survival time president of the object to the logic survival time until other strong references no longer exists. Such objects appear too much can cause the virtual machine memory footprint increase in the program, and finally produce OOM error. To solve this problem, we need careful attention to management on a strong reference to the object. When an object is no longer need to refer explicitly remove these strong reference. But this will developers to put forward higher requirements. A better approach is to use weak references Alternatively strong references to refer to these objects. So that both can refer to objects, and also avoid problems caused by strong references.
4) Map subclasses WeakHashMap typical application is the application of weak references, it can be as simple cache solution. WeakHashMap in java.util package, which implements the Map interface, HashMap is an implementation that uses weak references as internal data storage scheme.
If you need a lot of Map Table in the system, Map of entries as the cache purposes, this also means that even without the Map acquired from the corresponding data, the system can also obtain these data through the candidate. Although this will consume more time, but does not affect the normal operation of the system. In this scenario, use WeakHashMap is the most suitable. Because WeakHashMap will be within the range of system memory, save all entries, but once is not enough memory in the GC is not referenced entries will soon be removed, so as to avoid the system out of memory.

 @Test
    public void mapTest() {
        Map<Integer, byte[]> map1 = new WeakHashMap<>();
        long startTime = System.currentTimeMillis();
        List list = new ArrayList();
        for (int i = 0; i < 100000; i++) {
            Integer iWrap = Integer.valueOf(i);
            map1.put(iWrap, new byte[i]);

        }
        System.out.println ( "elements into the HashMap time consumption" + (System.currentTimeMillis () - startTime ) / 1000 + " s" );
    }

 

The code will be reported abnormal, heap space error, the memory overflow;
Here Insert Picture Description
but if the "Map <Integer, byte [] > map1 = new HashMap <> ();" changed "Map <Integer, byte [] > map1 = new WeakHashMap <> (); " , the memory overflow problem does not occur.
Here Insert Picture Description
Also, if while using the WeakHashMap, still in the loop added list.add (iWrap), it will still be the problem of memory overflow occurs. Because "list.add (iWrap);" This line of key references were strong, will lead to WeakHashMap not start instance auto-recovery mechanisms. So, if by WeakHashMap automatically clean up the data, try not strong references WeakHashMap of key systems elsewhere in the system, otherwise the key will not be recovered, WeakHashMap they will not be able to release the memory occupied by normal.
5) Weak references the difference / differences between soft cited
general, weak reference object different from the maximum soft reference objects is that, when a recovery performing GC, Soft references required by the algorithm checks whether the recovery, and for the weak references objects, GC is always recovered. Weak reference object easier, faster recovered GC. Although, GC must reclaim Weak objects at runtime, but weak target group often requires complex relationship GC run several times to complete. Scenario as described above, a weak reference object Map structures are often used, a large amount of data referenced object, once the object reference is a strong null, GC object space can be recovered rapidly.

6. The virtual reference (the PhantomReference)

1) references virtual, also known as ghost references, is one of the weakest intensity reference type, represented by java.lang.ref.PhantomReference class. The main purpose of phantom reference is to be notified before an object occupies memory is actually recycled, which can be related to some of the cleanup work. Specter cited in use and before the introduction of two reference types are very different: first virtual reference must provide a reference queue as a parameter when creating; get method followed by the phantom reference object always returns null, and therefore can not be false by Gets a reference to the object being referenced.
2) references virtual object is used to track the main garbage collector activities recovered. With reference to a virtual reference difference between the soft and weak reference is that: the virtual reference and reference must queue (the ReferenceQueue) used in combination. When the garbage collector is ready recovery of an object, it is found that if there is a virtual reference, will be recovered before the memory, this reference is added to the virtual queue associated with a reference.
3) Virtual references cited soft / weak references distinction
Soft and weak references could be added to the corresponding reference queue is in its up state is reached. That is, when an object becomes soft or weak references cited up time up, point the object referenced objects can be added to the reference queue. Before you add to the queue, the garbage collector will remove its reference to the relationship between the referenced object. When the soft and weak references into the queue, finalize the method object may not be invoked. After finalize the implementation of the method, the object is likely to return unreachable. If the object is returned to the up state, and points to the soft reference object or weak reference object reference relationship has been cleared, then you can not locate the object by reference to the object. The specter of reference is different, only after finalize method of the object is run, the specter of reference will be added to the queue. Soft and weak references are different, the ghost reference before being added to the queue, the garbage collector does not automatically clear the reference relationship, call clear method to explicitly clear. When the specter of references is cleared, the object entered the unreachable state, the garbage collector can reclaim their memory. When the ghost reference is added to the queue, since the class PhantomReference always get method returns null, the program can not be referenced object points specter of any operation.

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;

public class RefQueue {
    static class RefObj {
        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            System.out.println ( "the Finalize method is called" );
        }
    }


    public static void phantomReferenceQueue() {
        ReferenceQueue<RefObj> queue = new ReferenceQueue<>();
        RefObj obj = new RefObj();
        PhantomReference<RefObj> phantomRef = new PhantomReference<>(obj, queue);
        obj = null;
        Reference<? extends  RefObj> ref = null;
        while ((ref = queue.poll()) == null) {
            System.gc();
        }
        phantomRef.clear();
        System.out.println(ref == phantomRef);
        System.out.println ( "Ghost references are clear" );
    }

    public static void main(String[] args) {
        phantomReferenceQueue();
    }
}

 

Console Print
Here Insert Picture Description

 

Guess you like

Origin www.cnblogs.com/gocode/p/introduction-to-four-reference-types-in-java.html