SunToolkit.awtLock:需要在EDT上调用需要这种锁的代码

时间:2013-04-16 11:32:40

标签: java swing awt

我正在调查死锁并在线程转储中看到以下内容

at sun.awt.SunToolkit.awtLock(SunToolkit.java:229)
at sun.awt.X11.XRobotPeer.setup(Native Method)
- locked <0x00000000a633fbd0> (a java.lang.Class for sun.awt.X11.XRobotPeer)
at sun.awt.X11.XRobotPeer.<init>(XRobotPeer.java:24)
at sun.awt.X11.XToolkit.createRobot(XToolkit.java:683)
at java.awt.Robot.init(Robot.java:119)
at java.awt.Robot.<init>(Robot.java:77)

这是由致电Robot robot = new Robot();

引起的

此调用需要锁定(SunToolkit.awtLock),我想知道还有谁在使用该锁定,如果我将new Robot()调用移至EDT会更好。该名称表明AWT使用它是单线程的。如果EDT上的某些东西也采用了这种锁(例如Swing组件),那么当我在EDT上创建Robot时,我遇到死锁的几率会增加。

另一方面,正如this question中所讨论的,许多Robot方法被设计为在EDT上调用时抛出异常。如果你最好在EDT上创建Robot实例,这会让人讨厌。

Toolkit.getDefaultToolkit().getScreenResolution()存在同样的问题,因此无需专注于Robot类:

at sun.awt.SunToolkit.awtLock(SunToolkit.java:229)
at sun.awt.X11.XToolkit.getScreenResolution(XToolkit.java:999)

所以我想要清理的是:

  • 锁定中谁是有兴趣的人?
  • 这个锁是否只是为了尝试使Swing / AWT多线程(或至少更多线程安全)而引入,但推荐的方法是避免在另一个线程上接受EDT的锁定?
  • 是否有可用的官方Oracle / Sun文档(类似于Swin中的Concurrency指南),我可以参考吗?我的Google技能在此失败了。

1 个答案:

答案 0 :(得分:1)

在此处查看SunToolkit.java的源代码:http://www.docjar.com/html/api/sun/awt/SunToolkit.java.html AWT_LOCK的目的在第208行解释。

如果页面消失,请点击以下内容:

/** 
 * The AWT lock is typically only used on Unix platforms to synchronize
 * access to Xlib, OpenGL, etc.  However, these methods are implemented
 * in SunToolkit so that they can be called from shared code (e.g.
 * from the OGL pipeline) or from the X11 pipeline regardless of whether
 * XToolkit or MToolkit is currently in use.  There are native macros
 * (such as AWT_LOCK) defined in awt.h, so if the implementation of these
 * methods is changed, make sure it is compatible with the native macros.
 *   
 * Note: The following methods (awtLock(), awtUnlock(), etc) should be
 * used in place of: 
 *     synchronized (getAWTLock()) {
 *         ... 
 *     }   
 *   
 * By factoring these methods out specially, we are able to change the 
 * implementation of these methods (e.g. use more advanced locking
 * mechanisms) without impacting calling code.
 *   
 * Sample usage:
 *     private void doStuffWithXlib() {
 *         assert !SunToolkit.isAWTLockHeldByCurrentThread();
 *         SunToolkit.awtLock();
 *         try {
 *             ... 
 *             XlibWrapper.XDoStuff();
 *         } finally {
 *             SunToolkit.awtUnlock();
 *         }   
 *     }   
 */