Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

How does weak Reference work in Java

I have the following code :

public class Test {
  public static void main(String[] args) throws InterruptedException {
      String s = "test";
    WeakReference<String> s2 = new WeakReference<String>("test");
 s = null;



Open in new window

Here i tried to create a weakReference to the same string object..
And then set the strong reference to null.. and ran gc... Waited for garbage collector to run and clear all weakReferences...
But still i see s2.get() returning "test" ?? how is that possible...
Why doesnt garbage collector set the value in s2 as null.
What i understand is since the string "test" now does not have any strong reference to it.. It will be Garbage collected .

Avatar of CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rohit Bajaj


What is the basic difference between the two...
Your code seems to be working...
Wont s = "test"  and doing s = new String("test")  same string test... ?
Although i understand that
doing new String  will always create a new string whereas using the = operator....will use string pools and wont create a new string if a string is already there...
Let's back up a bit. If it's your goal to use/understand WeakReference, i would not use String, as it's a special case. Use Object for now
yes... Got it.. using an Object is clear...
Just for learning sake if you could explain why above String case was not working ?
Actually you explained it yourself. With a literal assignment and without the use of explicit creation, the String will be placed in the pool and will remain there.