ThreadBocal init上的FindBugs警告

时间:2015-09-04 16:08:25

标签: java findbugs thread-local

我的ThreadLocal实例已使用重写的initValue方法初始化。我还用@edu.umd.cs.findbugs.annotations.SuppressWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")注释了它如下。

@edu.umd.cs.findbugs.annotations.SuppressWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
private ThreadLocal<Integer> dbSwitchCount=new ThreadLocal<Integer>() {
    @Override 
    protected Integer initialValue() {
        return 0;
    }
};

Still Sonar报告抱怨&#34;性能 - 可以重新计入一个命名的静态内部类&#34;。 我怎样才能确保上述抱怨被忽略或者我能避免抱怨的最佳方式。

2 个答案:

答案 0 :(得分:2)

做Sonar建议的“可以重新考虑到一个命名的静态内部类”。

命名的静态内部类:

class MyClass {
    static class MyThreadLocal extends ThreadLocal<Integer> {
        @Override 
        protected Integer initialValue() {
            return 0;
        }
    }
    private ThreadLocal<Integer> dbSwitchCount = new MyThreadLocal();
}

我认为Sonar认为这是“性能”改进的原因是因为匿名类是非静态的,并且使其静态可以改善内存管理。

答案 1 :(得分:1)

注释不起作用,因为您正在注释dbSwitchCount字段,而不是匿名类,并且错误报告未绑定到该字段。以下是XML报告中的错误报告:

<BugInstance type="SIC_INNER_SHOULD_BE_STATIC_ANON" priority="3" rank="20" abbrev="SIC" 
             category="PERFORMANCE" first="1">
  <Class classname="MyClass$1">
    <SourceLine classname="MyClass$1" start="1" end="10" 
                sourcefile="MyClass.java" sourcepath="MyClass.java"/>
  </Class>
  <SourceLine classname="MyClass$1" start="7" end="7" startBytecode="0" endBytecode="0" 
              sourcefile="MyClass.java" sourcepath="MyClass.java"/>
</BugInstance>

请参阅dbSwitchCount字段。因此,当suppress-filter工作时,它不知道dbSwitchCount注释以某种方式与此错误报告相关联。不幸的是,我认为无法对匿名类本身进行注释。在不更改实际代码的情况下,唯一能够抑制此警告的方法是注释外部类:

@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
public class MyClass {

    private final ThreadLocal<Integer> dbSwitchCount=new ThreadLocal<Integer>() {
        @Override 
        protected Integer initialValue() {
            return 0;
        }
    };
}

这样警告就会消失(顺便说一下,建议改为使用@SuppressFBWarnings注释)。

通常,实例绑定(非静态)线程局部可疑。例如,请参阅this question。因此,最初的问题可能是dbSwitchCount应该声明为静态(这样SIC_INNER_SHOULD_BE_STATIC_ANON警告也会消失。)

更新我检查了此探测器的FindBugs代码。看起来可以添加缺失的bug注释,以便可以抑制注释字段或封闭方法的警告。我在我们的错误跟踪器中创建了一个ticket

UPDATE-2 Fixed in FindBugs trunk