Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java's garbage collection - is nulling every object explicitly considered a good style?

Someone suggested to me recently that to avoid hogging the memory, a Java application should always destroy all objects created in the method at the end of this method whenever it's possible (by setting it to null).

I haven't seen that done too often before, and from my point of you it seems to defeat the purpose of garbage collector in the first place. Are there any guidelines / reasoning when this strategy is useful? Would you ever face an application when this is necessary if you are careful about your objects?

like image 791
Nikita Avatar asked Dec 27 '22 18:12

Nikita


2 Answers

Setting references to null doesn't destroy the objects. It just eliminates one reference to them. In order for the memory to be freed, the garbage collector is still required. For locally scoped variables, this makes no difference at all.

like image 176
recursive Avatar answered Feb 11 '23 06:02

recursive


Many years ago this was recommended by some as a way to help the Garbage Collector identify which objects should be garbage collected. Today's GC is very sophisticated and generally needs no help from the developer. In fact, you're more likely to introduce bugs this way (e.g. accidentally nulling a variable prematurely).

This question was asked many times before. Here's one other thread: Does assigning objects to null in Java impact garbage collection?

like image 31
Steve Brisk Avatar answered Feb 11 '23 05:02

Steve Brisk