We help IT Professionals succeed at work.

How does weak Reference work in Java

Rohit Bajaj
Rohit Bajaj asked
on
161 Views
Last Modified: 2017-03-10
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

CERTIFIED EXPERT
Top Expert 2016
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

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...
CERTIFIED EXPERT
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 ?
CERTIFIED EXPERT
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.