Do you know four kinds of reference types in Java?

Source: Internet
Author: User

From a freshman self-taught Java has been two years, conscious already can independently, (in fact, far less), has been reading recently. About Java four kinds of reference types, I also just understand, hereby note!

Four levels of references are available in Java: Strong references, soft references, weak references, and virtual references. Of these four reference types, only the strongly referenced Finalreference class is visible within the package, and the other three reference types are public and can be used directly in the application. The class structure of the reference type.

1. Strong references

A reference in Java, similar to the most difficult pointer in C language. (I am the C language Primer, the concept of pointers is still very deep in my heart.) By reference, you can manipulate objects in the heap. Such as:

StringBuffer stringBuffer = new StringBuffer("Helloword");

The variable str points to the heap space where the StringBuffer instance resides, and can manipulate the object through Str.

Features of strong references:

    1. A strong reference can directly access the target object.
    2. The object that the strong reference points to is not reclaimed by the system at any time. The JVM prefers to throw an oom exception, nor does it reclaim the object that the strong reference points to.
    3. A strong reference can cause a memory leak.
2. Soft references

Soft references are the strongest reference types in addition to strong references. Soft references can be used through java.lang.ref.SoftReference. An object that holds soft references will not be recovered by the JVM very quickly, and the JVM will determine when to recycle based on the current heap usage. A soft-referenced object is reclaimed when the heap usage is near the threshold. Therefore, soft references can be used to implement memory-sensitive caches.

The SoftReference feature is that an instance of it holds a soft reference to a Java object, and the existence of the soft reference does not prevent the garbage collection thread from reclaiming the Java object. That is, once SoftReference has saved a soft reference to a Java object, the Get () method provided by the SoftReference class returns a strong reference to the Java object before the garbage thread recycles the Java object. Once a garbage thread reclaims the Java object, the Get () method returns NULL.

Here is an example of how soft references are used.

Set the parameters in your IDE -Xmx2m -Xms2m to specify a heap memory size of 2m.

    @Test    public void test3(){        MyObject obj = new myObject();        SoftReference sf = new SoftReference<>(obj);        obj = null;        System.gc();//        byte[] bytes = new byte[1024*100];//        System.gc();        System.out.println("是否被回收"+sf.get());    }

Operation Result:

是否被回收[email protected]

Open the commented out new byte[1024*100] statement, which requests a large heap of space to make heap memory use tense. and explicitly call the GC again, the results are as follows:

是否被回收null

Note that soft references are recycled in case of system memory constraints.

3. Weak references

A weak reference is a reference type that is weaker than a soft reference. In a system GC, objects are recycled whenever a weak reference is found, regardless of the adequacy of the system heap space. In Java, you can use a java.lang.ref.WeakReference instance to hold a weak reference to a Java object.

    public void test3(){        MyObject obj = new MyObject();        WeakReference sf = new WeakReference(obj);        obj = null;        System.out.println("是否被回收"+sf.get());        System.gc();        System.out.println("是否被回收"+sf.get());    }

Operation Result:

是否被回收[email protected]是否被回收null

Soft references, weak references are well suited to save those unwanted cache data, and if you do, the cached data will be reclaimed when the system is running out of memory, without causing memory overflow. When memory resources are plentiful, these cached data can exist for quite a long time, thus accelerating the system's function.

4. Virtual References

A virtual reference is the weakest of all types. An object that holds a virtual reference is almost the same as no reference, and can be reclaimed by the garbage collector at any time. When you try to get a strong reference by a virtual reference, the Get () method always fails. Also, a virtual reference must be used in conjunction with a reference queue, which is designed to track the garbage collection process.

When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will destroy the object after garbage collection and add the virtual reference to the reference queue. The program can see if the referenced object is going to be garbage collected by judging whether the reference queue has been added to the virtual reference. If the program discovers that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is reclaimed.

    public void test3(){        MyObject obj = new MyObject();        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();        PhantomReference sf = new PhantomReference<>(obj,referenceQueue);        obj = null;        System.out.println("是否被回收"+sf.get());        System.gc();        System.out.println("是否被回收"+sf.get());    }

Operation Result:

是否被回收null是否被回收null

A get () operation on a virtual reference always returns NULL, because the Sf.get () method is implemented as follows:

    public T get() {        return null;    }
5.WeakHashMap class and its implementation

The Weakhashmap class in the Java.util package, which implements the map interface, is an implementation of HASHMAP, which uses weak references as the storage scheme for internal data. Weakhashmap is a typical application of weak references, which can be used as a simple caching table solution.

Two pieces of code to save a large amount of data using Weakhashmap and HashMap, respectively:

    @Test    public void test4(){        Map map;        map = new WeakHashMap<String,Object>();        for (int i =0;i<10000;i++){            map.put("key"+i,new byte[i]);        }//        map = new HashMap<String,Object>();//        for (int i =0;i<10000;i++){//            map.put("key"+i,new byte[i]);//        }    }

Using -Xmx2M qualified heap memory, code that uses Weakhashmap ends properly, and code snippets that use HashMap throw exceptions

java.lang.OutOfMemoryError: Java heap space

This shows that Weakhashmap will use weak references when the system is out of memory and automatically release memory data that holds weak references.

However, if Weakhashmap key has strong references within the system, then weakhashmap is degraded to normal hashmap because all the table entries cannot be automatically cleaned up.

Do you know four kinds of reference types in 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.