根据FindBugs 错误描述:
ST:从实例方法写入静态字段(ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD)
此实例方法写入静态字段。如果正在操纵多个实例,这很难纠正,而且通常是不好的做法。
除了并发问题,这意味着 JVM 中的所有实例都在访问相同的数据,并且不允许两组单独的实例。如果您有一个单例“管理器”对象并将其作为构造函数参数或至少作为setManager()
方法参数传递给每个实例,那就更好了。
至于并发问题:如果你必须使用静态字段,你的静态字段应该是最终的;显式同步很困难。(如果您要初始化非最终静态字段,还有一些棘手的方面,超出了我对 Java 的了解,但我想我已经在 Java Puzzlers 书中看到了它们。)至少有三种处理方法(警告,未经测试的代码如下,使用前先检查):
使用线程安全的集合,例如Collections.synchronizedList
包裹在不以任何其他方式访问的列表周围。
static final List<Item> items = createThreadSafeCollection();
static List<Item> createThreadSafeCollection()
{
return Collections.synchronizedList(new ArrayList());
}
然后当您从一个实例替换此集合时:
List<Item> newItems = getNewListFromSomewhere();
items.clear();
items.add(newItems);
这样做的问题是,如果两个实例同时执行此序列,您可能会得到:
实例1:items.clear(); Instance2: items.clear(); Instance1: items.addAll(newItems); Instance2: items.addAll(newItems);
并获得一个不满足所需类不变量的列表,即静态列表中有两组 newItems。因此,如果您将整个列表作为一个步骤清除,然后将项目作为第二个步骤添加,则此方法不起作用。(但是,如果您的实例只需要添加一个项目,items.add(newItem)
则可以安全地从每个实例中使用。)
同步对集合的访问。
您需要一个显式的同步机制。同步方法不起作用,因为它们在“this”上同步,这在实例之间并不常见。你可以使用:
static final private Object lock = new Object();
static volatile private List<Item> list;
// technically "list" doesn't need to be final if you
// make sure you synchronize properly around unit operations.
static void setList(List<Item> newList)
{
synchronized(lock)
{
list = newList;
}
}
使用原子参考
static final private AtomicReference<List<Item>> list;
static void setList(List<Item> newList)
{
list.set(newList);
}