How does weak Reference work in Java

Rohit Bajaj
Rohit Bajaj used Ask the Experts™
on
Hi,
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;
     
   System.gc();
        
Thread.sleep(1000);
      
  System.out.println(s2.get());


  
  }

}

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 .

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016
Commented:
Your code is wrong. Should be

 
      String s = new String("test");
        WeakReference<String> s2 = new WeakReference<String>(s);

Open in new window

Author

Commented:
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...
Top Expert 2016

Commented:
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

Author

Commented:
yes... Got it.. using an Object is clear...
Just for learning sake if you could explain why above String case was not working ?
Top Expert 2016

Commented:
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.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial