Reference Soft Strong Weak

    技术2022-05-20  52

    今天被问及了应用的区别,具体如下

    参考一下understanding-weak-reference

     

    four different degrees of reference strength: strong, soft, weak, and phantom, in order from strongest to weakest.

     

    Strong Reference 主要是只通过 Object obj = new Object()这种方式产生的应用.

    Strong Reference 只有在obj == null 的情况下, 对象才会在GC的时候被回收。

     

    SoftReference 的目的是在当应用为0的情况下,仍然不会回收该对象,知道JVM内存不够用的时候就会被回收。

    an object which is softly reachable will generally stick around for a while.

     

    WeakReference

    String因为是放入常量池因此

    WeakHashMap<Object , String> weakMap = new WeakHashMap<Object, String>(); //如果这里用String作为Key的话,就无法起到WeakReference的效果 Object key1 = new Object(); weakMap.put(key1, new Object().toString()); System.out.println(weakMap); key1 = null; System.gc(); //Thread.sleep(5000); System.out.println(weakMap);

     

     


    最新回复(0)