Avatar of Rohit Bajaj
Rohit Bajaj
Flag 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 undefined
Last Comment

8/22/2022 - Mon

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
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
Rohit Bajaj

yes... Got it.. using an Object is clear...
Just for learning sake if you could explain why above String case was not working ?
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck

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.