WeakReference and SoftReference in Java, javaweakreference

Source: Internet
Author: User

WeakReference and SoftReference in Java, javaweakreference

We know that there are no pointers in the Java language, instead we will reference the reference. There are four types of references in Java: strong reference, weak reference, SoftReference, and PhantomReference ). Strong references are the most common references we usually use. Virtual references are generally unavailable. So we will mainly understandWeakReference and SoftReference(In addition to the four references mentioned above, there is also a reference-atomic referenceAtomicReferenceFor concurrent programming environments ).

1.First, run the following code:

public class ReferenceTest {    public static void main(String[] args){        LinkedList<byte[]> list = new LinkedList<>();        for(int i=0; i<1024; i++){            list.add(new byte[1024*1024]);        }    }}

The above code will throw:Exception in thread "main" java. lang. OutOfMemoryError: Java heap space

Heap memory overflow. Because we constantly allocate a 1 MB byte [] object on the stack and add this reference to the list. This will take up 1 GB of heap memory for 1024 cycles, this causes heap space OutOfMemory.

2.We useWeekReferenceModify the Code:

public class ReferenceTest {    public static void main(String[] args) {        long beginTime = System.nanoTime();        LinkedList<WeakReference<byte[]>> list = new LinkedList<>();        for (int i = 0; i < 1024; i++) {            list.add(new WeakReference<>(new byte[1024 * 1024]));        }        long endTime = System.nanoTime();        System.out.println(endTime - beginTime);    }}

Output result: 195947704 (0.19 seconds)

The heap memory overflow error is missing. What is the reason. Because we use the weak reference WeekReference to reference the 1 M byte [] object on the stack,However, if the WeekReference object is referenced only by weak references but not by strong references, the memory occupied by the object will be recycled in the next GC.So the memory will not overflow.

3.We useSoftReferenceModify the Code:

public class ReferenceTest {    public static void main(String[] args) {        long beginTime = System.nanoTime();        LinkedList<SoftReference<byte[]>> list = new LinkedList<>();        for (int i = 0; i < 1024; i++) {            list.add(new SoftReference<>(new byte[1024 * 1024]));        }        long endTime = System.nanoTime();        System.out.println(endTime - beginTime);    }}

Output result: 1499904286 (1.5 seconds)

We found that the heap memory overflow error is also absent. Because we use soft reference SoftReference to reference the 1 M byte [] object on the stack,Soft reference SoftReference: If the referenced object is only soft reference but not strongly referenced, GC will reclaim the memory occupied by the object when the memory space is insufficient.So the memory will not overflow.

However, we have noticed that the difference between WeekReference and SoftReference is close to 10. The reason should be that SoftReference recycles the space occupied by the object only when the memory space is insufficient. In this case, full GC is performed, and full GC will cause the STW program to be suspended, therefore, it takes too much time.

4.Summary

Strong reference: as long as the object on the stack is pointed to by at least one strong reference, GC will not recycle the memory space of the object.

Weak reference: as long as the objects on the stack are only pointed to by weak references, the memory space of the objects will be reclaimed next time no matter whether the current memory space is sufficient.

Soft reference: GC recycles the object's memory space as long as the object on the stack is only pointed to by soft reference and when the memory space is insufficient.

WeakReference and SoftReference are generally used to construct a cache system, for example, a map. Because the cache system is a "full life" object, the system stops and the cached object will be destroyed. Therefore, when we constantly want to add objects to the cache, as a result, the cached object map will reference more and more objects. Because it is a strong reference, these objects put into the map cache cannot be recycled by the GC lock, as a result, the system heap memory usage increases, leading to memory overflow.

In this case, we can use WeakReference or SoftReference. After the strong reference is packaged through WeakReference and SoftReference, it becomes weak reference and soft reference. Then, when the objects in the cache are, only when referenced by the cached map lock, the memory occupied by these objects will be reclaimed in the next GC and GC with insufficient memory. In fact, JDK provides us with a specialized class: WeakHashMap and weak referenced hashMap. Therefore, to construct a cache system, we can consider using it.

In fact, many maps in jdk are involved here. How should we choose them:

HashMap

ConcurrentHashMap

TreeMap

WeakHashMap

LinkedHashMap

Collections. synchronizedMap

Hashtable

And so on. When selecting a map, we should take it into consideration, which is more suitable for our needs.

 

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.