查找事件派发线程违规

时间:2011-12-16 01:47:22

标签: java swing code-analysis event-dispatch-thread

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

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

人们通常采取什么方法?

4 个答案:

答案 0 :(得分: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());
    }
  }
}

答案 1 :(得分:4)

我只是小心,我自己。但是你可以安装代码来测试给定的代码段是否在SwingUtilities.isEventDispatchThread()的调度线程中执行,如果不是(或者如果有的话),你可以做你喜欢的。

答案 2 :(得分:3)

Substance Look and Feel包含自动runtime EDT violation checker。它可以帮助在测试时捕获EDT违规。检测到违规时,它会抛出IllegalStateException。这对测试很有用。

答案 3 :(得分:0)

Fest's swing module还包含您可以安装的EDT violtion checker,在检测到违规时会抛出异常。