PMD report NullAssignment
of the following code, what is the best practice to fix it?
Assigning an Object to null is a code smell. Consider refactoring.
This code is written in the false believe that a reference that is set to null
is garbage collected faster.
Therefore the message from PMD is that this false believe was coded.
This is a wrong assumption as the garbage collector runs when the memory is exhausted and it collects all objects that have no reference left on them.
Even calling System.gc()
will not cause the garbage collector to run. The call is merely a hint to the garbage collector but when the garbage collector detemines that enough free memory is avaible it will not run.
Assigning an Object to null is a code smell.
IMHO
After setting the Object/variable to null
you can call System.gc()
which forces the garbage collector to run Right Now.
I believe there will be no violations and code smell in that.
Reached this post while searching for other info, and noticed none of previous answers are right (IMO).
The reason for the null assignment in supplied code is obviously not about garbage collecting, but about being able to stop and recreate new timers, only one timer being able at a time.
I don't see any reason for using the temporary variable on the stopTimer
method, but looks unrelated to original issue.
I would say this code is fine, and a SuppressWarnings("PMD.NullAssignment")
annotation could be added to avoid the violation; PMD is just highlighting null assignments are usually a smell, not a fact of any issue.