Do not look for a thorough analysis of the text weak references in Java (refer to the official website)

Class definition and location:

package java.lang.ref
  public class WeakReference<T> extends Reference<T> {
 }
复制代码

effect:

jdk official website explained:

The main weak reference implementation does not stop its key or value recovered mapping. Directly attached to the English bar, limited the level of translation (weak references are for implementing canonicalizing mappings that do not prevent their keys (or values) from being reclaimed)

Personal understanding:

Its role is to refer to an object, but does not prevent the object from being recycled. If you use a strong reference, so long as the reference exists, then the referenced objects can not be recycled. A weak reference does not have this problem. When the garbage collector runs, if all references to an object are weak references, then the object will be recycled

For example:

Before I first explain the weak reference example cited under strong contrast to facilitate understanding:

Strong well understood is what we usually quote a new object. E.g:

  String str = new String("我是强引用");
复制代码

The garbage collector has a reachability determination, if a strong reference, so long as the reference exists, then the object referenced can not be recovered; just a little difficult to see the text understood that the following example


public class StrongRefenceDemo {


    static Map<String, String> map;

    public static void main(String[] args) throws Exception {

        StrongRefenceDemo demo = new StrongRefenceDemo();
        demo.strongTest();
        System.out.println("gc 发生前:" + map.get("str"));
        System.out.println("开始通知GC");
        //注意,这里只是通过垃圾回收器进行垃圾回收,并不一定马上执行
        System.gc();
        Thread.sleep(1000 * 5);
        System.out.println("gc 发生后:" + map.get("str"));

    }


    /**
     * 强引用测试
     */
    public void strongTest() {
        String str = new String("我被强引用引用,但是我还没有被垃圾回收");
        map = new HashMap();
        map.put("str", str);
    }

}
复制代码

After running output:

gc 发生前:我被强引用引用,但是我还没有被垃圾回收
开始通知GC
gc 发生后:我被强引用引用,但是我还没有被垃圾回收

复制代码

I believe we no doubt, after all, is still a strong reference str map references, the garbage collector can not reclaim it on the above results.

But here I have a curious, if str where the object pointed thrown away after executing the strongTest () method, but I'm not a good judge may take the initiative to call remove to remove it. Want to judge for themselves the garbage collector reclaim lost this possible? The answer is actually possible, this time is playing a weak reference, see the following procedures


public class WeakRefenceDemo {
    static WeakReference<String> weakReference;
    public static void main(String[] args) throws Exception {

        WeakRefenceDemo demo = new WeakRefenceDemo();
        demo.weakTest();
        System.out.println("gc 发生前:" + weakReference.get());
        System.out.println("开始通知GC");
        //注意,这里只是通过垃圾回收器进行垃圾回收,并不一定马上执行
        System.gc();
        Thread.sleep(1000 * 5);
        System.out.println("gc 发生后:" + weakReference.get());

    }

    /**
     * 弱引用测试
     */
    public void weakTest() {
        String str = new String("我被弱引用引用,但是我还没有被垃圾回收");
        weakReference = new WeakReference(str);
    }


}

复制代码

Run the above code output

gc 发生前:我被弱引用引用,但是我还没有被垃圾回收
开始通知GC
gc 发生后:null
复制代码

Operating results analysis:

Here we see the output is null is meant has been garbage collected out. We also prove to be said weak reference above does not prevent the object from being recovered

scenes to be used

Under normal circumstances, the life cycle of an object should be the object it contains is consistent. Figuratively, I have a global map, then the lifetime of an object inside the map and it should be consistent. If you say that the life cycle of an object inside a map than the map itself the object of the life cycle is longer, when we do not take the initiative to call the remove method of the map, the garbage collector is not going to recover the lost object. If such a relatively short life cycle of many objects, it may eventually consume all of the JVM memory. Ideal state is actually a relatively short life cycle of these objects, at the end of its life cycle, even if we do not have to manually remove the call can also be recovered out of the garbage collector. For the solution to this situation is to use weak references to refer to these objects, so the hash table of key and value objects can be garbage collected. Java provides a common WeakHashMap to meet this demand.

In fact, there's a major usage scenarios is jdk inside the famous ThreadLocal, the next will be to write an article analyzing why there's ThreadLocal implemented using weak references to

jdk8 official document parsing weak references

Guess you like

Origin juejin.im/post/5d8b297e5188250b532eb013