Java:测试线程访问"非线程安全"方法

ama*_*ion 9 java user-interface aop unit-testing thread-safety

我在Swing Java应用程序中处理线程问题的策略是将方法划分为三种类型:

  1. 应该由GUI线程访问的方法.这些方法永远不应该阻塞,也可以调用swing方法.不是线程安全的.
  2. 应由非GUI线程访问的方法.基本上,这适用于所有(可能)阻塞操作,例如磁盘,数据库和网络访问.他们永远不应该称为摇摆方法.不是线程安全的.
  3. 两者都可以访问的方法.这些方法必须是线程安全的(例如同步)

我认为这是GUI应用程序的有效方法,通常只有两个线程.切割问题确实有助于减少竞争条件下的"表面积".当然需要注意的是,你从不会意外地从错误的线程中调用方法.

我的问题是关于测试:

是否有测试工具可以帮助我检查从正确的线程调用方法?我知道SwingUtilities.isEventDispatchThread(),但我真的在寻找使用Java注释或面向方面编程的东西,这样我就不必在程序的每个方法中插入相同的样板代码.

ama*_*ion 2

感谢您的所有提示,这是我最终提出的解决方案。这比我想象的要容易。该解决方案同时使用 AspectJ 和注释。它的工作原理如下:只需将一个注释(定义如下)添加到方法或类中,然后在开头插入对 EDT 规则违规的简单检查。特别是如果您像这样标记整个类,则只需少量的额外代码即可完成大量测试。

首先我下载了​​ AspectJ并将其添加到我的项目中(在 eclipse 中你可以使用AJDT

然后我定义了两个新的注释:

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

/**
 * Indicates that this class or method should only be accessed by threads
 * other than the Event Dispatch Thread
 * <p>
 * Add this annotation to methods that perform potentially blocking operations,
 * such as disk, network or database access. 
 */
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR})
public @interface WorkerThreadOnly {}
Run Code Online (Sandbox Code Playgroud)

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

/**
 * Indicates that this class or method should only be accessed by the 
 * Event Dispatch Thread
 * <p>
 * Add this annotation to methods that call (swing) GUI methods
 */
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR})
public @interface EventDispatchThreadOnly {}
Run Code Online (Sandbox Code Playgroud)

之后,我定义了执行实际检查的方面:

import javax.swing.SwingUtilities;

/** Check methods / classes marked as WorkerThreadOnly or EventDispatchThreadOnly */
public aspect ThreadChecking {

    /** you can adjust selection to a subset of methods / classes */
    pointcut selection() : execution (* *(..));

    pointcut edt() : selection() && 
        (within (@EventDispatchThreadOnly *) ||
        @annotation(EventDispatchThreadOnly));

    pointcut worker() : selection() && 
        (within (@WorkerThreadOnly *) ||
        @annotation(WorkerThreadOnly));

    before(): edt() {
        assert (SwingUtilities.isEventDispatchThread());
    }

    before(): worker() {
        assert (!SwingUtilities.isEventDispatchThread());
    }
}
Run Code Online (Sandbox Code Playgroud)

现在将 @EventDispatchThreadOnly 或 @WorkerThreadOnly 添加到应该线程限制的方法或类中。不要向线程安全方法添加任何内容。

最后,只需在启用断言的情况下运行(JVM 选项 -ea),您很快就会发现违规位置(如果有)。

作为参考,这里是Mark 提到的Alexander Potochkin的解决方案。这是一种类似的方法,但它检查应用程序中对 swing 方法的调用,而不是应用程序内的调用。这两种方法是互补的并且可以一起使用。

import javax.swing.*;

aspect EdtRuleChecker {
    private boolean isStressChecking = true;

    public pointcut anySwingMethods(JComponent c):
         target(c) && call(* *(..));

    public pointcut threadSafeMethods():         
         call(* repaint(..)) || 
         call(* revalidate()) ||
         call(* invalidate()) ||
         call(* getListeners(..)) ||
         call(* add*Listener(..)) ||
         call(* remove*Listener(..));

    //calls of any JComponent method, including subclasses
    before(JComponent c): anySwingMethods(c) && 
                          !threadSafeMethods() &&
                          !within(EdtRuleChecker) {
     if(!SwingUtilities.isEventDispatchThread() &&
         (isStressChecking || c.isShowing())) 
     {
             System.err.println(thisJoinPoint.getSourceLocation());
             System.err.println(thisJoinPoint.getSignature());
             System.err.println();
      }
    }

    //calls of any JComponent constructor, including subclasses
    before(): call(JComponent+.new(..)) {
      if (isStressChecking && !SwingUtilities.isEventDispatchThread()) {
          System.err.println(thisJoinPoint.getSourceLocation());
          System.err.println(thisJoinPoint.getSignature() +
                                " *constructor*");
          System.err.println();
      }
    }
}
Run Code Online (Sandbox Code Playgroud)