Understanding Java's Reference classes: SoftReference, WeakReference, and PhantomReference

前端 未结 4 2016
星月不相逢
星月不相逢 2020-11-30 17:30

Can someone explain the difference between the three Reference classes (or post a link to a nice explanation)? SoftReference > WeakReference >

4条回答
  •  囚心锁ツ
    2020-11-30 17:59

    String str = new String("hello, world");
    WeakReference ref = new WeakReference(str);
    str = null;
    
    if (ref != null) {                 
        System.gc(); 
        System.out.println(ref.get());
    }
    

    In this case, it will output null. The call to System.gc() is important here.

提交回复
热议问题