Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GC in Java Setter

In a Java setter method that assigns a new Object to a field such as:

public class MyClass
{
     private String s;
     public void mySetter(String newS) {
          s = newS;
     }
}

Does the previous String s get garbage collected after mySetter is called or should I null out s before I assign it to the new value?

public class MyClass
{
     private String s;
     public void mySetter(String newS) {
          s = null;
          s = newS;
     }
}
like image 757
Steven Roberts Avatar asked Dec 16 '22 03:12

Steven Roberts


1 Answers

Does the previous String s get garbage collected after mySetter is called or should I null out s before I assign it to the new value?

If your previous String s is not referenced anywhere then it will be. But it won't happen immmedialtely after mySetter is called. No need to set it to null.

like image 116
fastcodejava Avatar answered Dec 17 '22 16:12

fastcodejava