Search code examples
androidweak-references

Why WeakReference still return the Object's Value?


I wanna know how to use WeakReference in developing android application.So as i searched a lot in the internet i typed this code :

   {
        String kk = "Test";
        WeakReference<String> kkRef = new WeakReference<String>(kk);
        System.out.println(kk);
        System.out.println(kkRef.get());
        kk = null;
        System.gc();
        System.out.println(kk);
        System.out.println(kkRef.get());
   }

which suppose to eligible the kk object to GC, But in the console output it seems that kkRef.get() still return the "Test" value which supposed to return null as i read about weakReference

So Why it didn't return null?


Solution

  • First, System.gc() does not necessarily perform a full garbage collection run, and there is no guarantee that it will do so synchronously. Hence, it is not guaranteed to detect all weakly-held objects.

    Second, the string is still held onto strongly, as it is a string literal in your code. That cannot be garbage collected ever, and so a WeakReference to it would still return the literal.