如何修复 pmd 违规“NullAssignment"? [英] How to fix pmd violation "NullAssignment"?

查看:60
本文介绍了如何修复 pmd 违规“NullAssignment"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PMD 报告 NullAssignment 以下代码,修复它的最佳做法是什么?

PMD report NullAssignment of the following code, what is the best practice to fix it?

将对象分配为 null 是一种代码异味.考虑重构.

Assigning an Object to null is a code smell. Consider refactoring.

以下代码不是我写的,我也有疑问,为什么创建一个临时的定时器实例,然后将这个实例分配给定时器?startTimerstopTimer 将在多线程上下文中使用.

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

推荐答案

这段代码是在错误的情况下编写的,相信设置为 null 的引用会被垃圾回收更快.

This code is written in the false believe that a reference that is set to null is garbage collected faster.

因此来自 PMD 的消息是这个错误的信念是被编码的.

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.

即使调用 System.gc() 也不会导致垃圾收集器运行.该调用只是对垃圾收集器的一个提示,但当垃圾收集器确定有足够的可用内存时,它将不会运行.

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.

这篇关于如何修复 pmd 违规“NullAssignment"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆