How to fix pmd violation “NullAssignment”?

前端 未结 3 1838
囚心锁ツ
囚心锁ツ 2021-01-23 19:42

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.

相关标签:
3条回答
  • 2021-01-23 19:59

    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.

    0 讨论(0)
  • 2021-01-23 20:07
      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.

    0 讨论(0)
  • 2021-01-23 20:20

    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.

    0 讨论(0)
提交回复
热议问题