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.
The following code is not written by me, I also have a question on why creating a temporary timer instance, then assign this instance to timer? startTimer
and stopTimer
will be used in multithread context.
private Timer timer;
private void startTimer() {
if (timer == null) {
Timer aTimer = timerService.createTimer(DEFAULT_TIMER_VALUE, null);
aTimer.setListener(this);
timer = aTimer;
}
}
private void stopTimer() {
if (timer != null) {
Timer aTimer = timer;
timer = null;
aTimer.cancel();
aTimer.setListener(null);
}
}
public void start() {
synchronized(..) {
startTimer();
}
}
public void stop() {
synchronized(..) {
stopTimer();
}
}
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.
来源:https://stackoverflow.com/questions/17590281/how-to-fix-pmd-violation-nullassignment