How to fix pmd violation “NullAssignment”?

五迷三道 提交于 2019-12-02 16:38:07

问题


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();
  }
}

回答1:


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.




回答2:


  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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!