0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

But i typed kk = null which remove the strong reference
@MohamedFadelBuffon: You removed that strong reference. The string literal still exists in your code. In Java, assignment (String kk = "Test") does not make a copy of the object. The string literal cannot be garbage collected. Try using an instance of an object that you create yourself using the new keyword.
Thank u very much it works for me :) . But could u please expalin to me what you meant by literal .. Thanks in advance
@MohamedFadelBuffon: A literal in Java is any primitive value (5, 3.14159f, true) or String ("Test") that you enter directly into your Java code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.