写入静态字段-在这种情况下FindBugs错误吗? [英] Write to static field - is FindBugs wrong in this case?

查看:97
本文介绍了写入静态字段-在这种情况下FindBugs错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的Java类:

I have a Java class like this:

public class Foo {

    public static int counter = 0;

    public void bar(int counter) {
        Foo.counter = counter;
    }
}

FindBugs警告我有关通过实例方法bar写入静态字段counter的信息.但是,如果我将代码更改为:

FindBugs warns me about writing to the static field counter via the instance method bar. However, if I change the code to:

public class Foo {

    public static int counter = 0;

    public static void setCounter(int counter) {
        Foo.counter = counter;
    }

    public void bar(int counter) {
        setCounter(counter);
    }
}

然后FindBugs不会抱怨.没错吗?我仍然只是通过静态方法从实例方法写入静态字段,不是吗?

Then FindBugs won't complain. Isn't that wrong? I'm still writing to a static field from an instance method, just via a static method, am I not?

推荐答案

假定在将来的某个时候,您确定此setter方法需要是线程安全的,并且您希望使其成为synchronized.

Suppose that at some point in the future, you decide this setter method needs to be thread safe and you want to make it synchronized.

此代码可以正常工作:

public synchronized static void setCounter(int counter) {
    Foo.counter = counter;
}

public void bar(int counter) {
    setCounter(counter);
}

此代码是错误的,将具有不正确的行为:

This code is wrong and will have incorrect behavior:

public synchronized void bar(int counter) {
    Foo.counter = counter;
}

在这个人为的示例中,这似乎没有太大的区别,尤其是因为通常可以仅将counter标记为volatile.但是,在一个真实的示例中,setter方法的逻辑更加复杂,并且在许多不同的地方(不仅仅是从一个实例方法中)被调用,后一种模式将更易于重构.

This might not seem like a significant difference in this contrived example, especially since counter can usually just be marked volatile. However, in a real world example where the setter method has more complicated logic and is being called from many different places (not just from one instance method), the latter pattern will be easier to refactor.

顺便说一句,我认为 Google的CodePro Analytix 插件是一个比FindBugs更快,更全面的工具.

As an aside, in my opinion Google's CodePro Analytix plugin is a much faster and more comprehensive tool than FindBugs.

相关:

  • Synchronized vs. Volatile in Java
  • Synchronized Getters and Setters

这篇关于写入静态字段-在这种情况下FindBugs错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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