I was recently looking into freeing up memory occupied by Java objects. While doing that I got confused about how objects are copied (shallow/deep) in Java and how to avoid
Java GC automatically claims the objects when they are not referenced anywhere. So in most cases you will have to set the reference as null
explicitly
As soon as the scope of the variable ends the object becomes eligible for GC and gets freed up if no other reference points to the object.
Java is pass by value so if you set the list as null
in the method then it will not affect the original reference that was passed to you in the method.
public class A{
private List list = new ArrayList();
public static void main(String[] args) {
A a = new A();
B b = new B();
b.method(a.list);
System.out.println(a.list.size()); //Will print 0 and not throw NullPointerException
}
}
class B{
public void method(List list){
list = null;
//just this reference is set to null and not the original one
//so list of A will not be GCed
}
}