查找事件派发线程违规

Mic*_*rry 4 java swing code-analysis event-dispatch-thread

我们都知道我们应该从事件调度线程完成所有与GUI相关的任务,否则可能会引入奇怪的错误 - 我试着记住这个规则,但我必须承认我最近注意到了几个我没有的地方.

有没有办法识别所有违反此规则的行为,以便修复它们?我已经看到这里有一个相关的findbugs规则,但它似乎并没有抓住我的所有情况.即使在发生违规时抛出异常也很好,所以我可以修复它(或者捕获异常并记录警告以防用户遇到相关问题.)

人们通常采取什么方法?

Jim*_*imN 5

一种方法是安装自定义重绘管理器,该管理器在EDT以外的线程上执行绘制时检测并记录.我们在我们的项目中使用这种方法,改编自以下博客:http://weblogs.java.net/blog/alexfromsun/archive/2006/02/debugging_swing.html.这不会检测所有类别的EDT线程违规,但它肯定比没有好.

更新:

评论者指出,链接的网页已不再可用.这是我的代码改编自博客帖子:

import javax.swing.JComponent;
import javax.swing.RepaintManager;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import sun.awt.AppContext;

public class DetectEdtViolationRepaintManager extends RepaintManager {

  private static final Logger LOGGER = Logger.getLogger(
    DetectEdtViolationRepaintManager.class);

  /**
   * Used to ensure we only print a stack trace once per abusing thread.  May
   * be null if the option is disabled.
   */
  private ThreadLocal alreadyWarnedLocal;

  /**
   * Installs a new instance of DetectEdtViolationRepaintManager which does not
   * warn repeatedly, as the current repaint manager.
   */
  public static void install() {
    install(false);
  }

  /**
   * Installs a new instance of DetectEdtViolationRepaintManager as the current
   * repaint manager.
   * @param warnRepeatedly whether multiple warnings should be logged for each
   *        violating thread
   */
  public static void install(boolean warnRepeatedly) {
    AppContext.getAppContext().put(RepaintManager.class, 
      new DetectEdtViolationRepaintManager(warnRepeatedly));
    LOGGER.info("Installed new DetectEdtViolationRepaintManager");
  }

  /**
   * Creates a new instance of DetectEdtViolationRepaintManager.
   * @param warnRepeatedly whether multiple warnings should be logged for each
   *        violating thread
   */
  private DetectEdtViolationRepaintManager(boolean warnRepeatedly) {
    if (!warnRepeatedly) {
      this.alreadyWarnedLocal = new ThreadLocal();
    }
  }

  /**
   * {@inheritDoc}
   */
  public synchronized void addInvalidComponent(JComponent component) {
    checkThreadViolations();
    super.addInvalidComponent(component);
  }

  /**
   * {@inheritDoc}
   */
  public synchronized void addDirtyRegion(JComponent component, int x, int y, 
    int w, int h) {
    checkThreadViolations();
    super.addDirtyRegion(component, x, y, w, h);
  }

  /**
   * Checks if the calling thread is called in the event dispatch thread.
   * If not an exception will be printed to the console.
   */
  private void checkThreadViolations() {
    if (alreadyWarnedLocal != null && Boolean.TRUE.equals(alreadyWarnedLocal.get())) {
      return;
    }
    if (!SwingUtilities.isEventDispatchThread()) {
      if (alreadyWarnedLocal != null) {
        alreadyWarnedLocal.set(Boolean.TRUE);
      }
      LOGGER.warn("painting on non-EDT thread", new Exception());
    }
  }
}
Run Code Online (Sandbox Code Playgroud)