用于查找 Java 中的共享可变数据错误的工具

我有一个大型的遗留系统需要维护。代码库到处使用线程,这些线程共享大量可变数据。我知道,听起来很糟糕。无论如何,不要回答“从头开始重写整个应用程序”,否则我会投票给你:-)我试图在代码库上运行一些静态分析工具,但这些工具似乎都没有抓住在我们的源代码中经常发生的情况:多个线程正在读取和写入根本不标记为易失性或同步的变量。通常,这发生在“runFlag”类型的变量上。这方面的一个例子是在有效的Java第2版第260页:

public class StopThread
{
    private static boolean stopRequested;
    public static void main(String[] args) throws InterruptedException
    {
        Thread backgroundThread = new Thread(new Runnable()
        {
            public void run()
            {
                int i = 0;
                while (!stopRequested)
                {
                    i++;
                }
            }
        });
        backgroundThread.start();
        Thread.sleep(1000);
        stopRequested = true;
    }
}

此示例永远不会在 Windows/Linux 上结束,并将“-server”启动参数提供给 Sun JVM。那么,是否有任何(半)自动方法可以找到这些问题,或者我必须完全依赖代码审查?


答案 1

Chris Grindstaff 写了一篇文章 FindBugs, Part 2: 编写自定义检测器,他在其中描述了如何使用 BCEL 添加自己的规则。(BCEL不是唯一的字节码库 - 但它是FindBugs使用的字节码库。

下面的代码发出方法访问静态方法或字段的任何情况。您可以在实现 Runnable 的任何类型上运行它。

public class StaticInvocationFinder extends EmptyVisitor {

    @Override
    public void visitMethod(Method obj) {
        System.out.println("==========================");
        System.out.println("method:" + obj.getName());

        Code code = obj.getCode();
        InstructionList instructions = new InstructionList(code.getCode());
        for (Instruction instruction : instructions.getInstructions()) {
            // static field or method
            if (Constants.INVOKESTATIC == instruction.getOpcode()) {
                if (instruction instanceof InvokeInstruction) {
                    InvokeInstruction invokeInstruction = (InvokeInstruction) instruction;
                    ConstantPoolGen cpg = new ConstantPoolGen(obj
                            .getConstantPool());
                    System.out.println("static access:"
                            + invokeInstruction.getMethodName(cpg));
                    System.out.println("      on type:"
                            + invokeInstruction.getReferenceType(cpg));
                }
            }
        }
        instructions.dispose();
    }

    public static void main(String[] args) throws Exception {
        JavaClass javaClass = Repository.lookupClass("StopThread$1");

        StaticInvocationFinder visitor = new StaticInvocationFinder();
        DescendingVisitor classWalker = new DescendingVisitor(javaClass,
                visitor);
        classWalker.visit();
    }

}

此代码发出以下内容:

==========================
method:<init>
==========================
method:run
static access:access$0
      on type:StopThread

然后可以扫描StopThread类型,找到该字段并检查它是否不稳定

检查同步是可能的,但由于多个 MONITOREXIT 条件,可能会变得棘手。向上移动调用堆栈也可能很困难,但这不是一个微不足道的问题。但是,我认为如果一致地实现了错误模式,那么检查它相对容易。

BCEL看起来很少记录,而且非常毛茸茸的,直到你找到BCELifier类。如果你在一个类上运行它,它会吐出Java源代码,说明你如何在BCEL中构建这个类。在 StopThread 上运行它,可以生成 access$0 综合访问器:

  private void createMethod_2() {
    InstructionList il = new InstructionList();
    MethodGen method = new MethodGen(ACC_STATIC | ACC_SYNTHETIC, Type.BOOLEAN, Type.NO_ARGS, new String[] {  }, "access$0", "StopThread", il, _cp);

    InstructionHandle ih_0 = il.append(_factory.createFieldAccess("StopThread", "stopRequested", Type.BOOLEAN, Constants.GETSTATIC));
    il.append(_factory.createReturn(Type.INT));
    method.setMaxStack();
    method.setMaxLocals();
    _cg.addMethod(method.getMethod());
    il.dispose();
  }

答案 2

最新版本的 FindBugs 将尝试检查标有注释的字段是否仅在相应的保护代码中访问。@GuardedBy