I read that Java is passed by value . So lets say we have this code and say that the HashMap somehashMap has a longer life time than foo . So foo is not allowed to be garbage collected even though it has done its work simply because we put foo inside the Map and then forgot to remove from it . Now going by the logic of the answer in the post that I linked to we are actually passing a copy of the reference of foo to the method put() right ?In that case putting the foo into the HashMap shouldn’t prevent it from getting garbage collected . Can you please help me understand what is going on here ? What am I missing exactly ?
public void someMethod(){
Foo foo = new Foo();
somehashMap.put(fooKey,foo);
}
Garbage collection isn’t applicable to references but to actual objects which reside in heap. When you put
fooin theMap, you are basically helping it “escape” out of its current scope and putting it in the same scope/life-time assomehashMap.References in Java are handled transparently behind the scenes. When you put the
fooreference in the map, a copy of the reference is actually passed to theputmethod call but the underlying object i.e.new Foo()is the same for both the original and the copied references. Let’s look at the below snippet:In the above snippet, how many objects are garbage collected after execution of
doItcompletes? It’s just the singlenew Object()which we created. Rest all are simply references or aliases which are used to point to the same object.