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

Rob*_*bin 8 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)
Run Code Online (Sandbox Code Playgroud)

这是由呼叫引起的 Robot robot = new Robot();

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

另一方面,正如在这个问题中讨论的那样,许多Robot方法被设计为在EDT上调用时抛出异常.如果您最好Robot在EDT上创建实例,这会让人讨厌.

存在同样的问题,Toolkit.getDefaultToolkit().getScreenResolution()所以不需要只关注这个Robot类:

at sun.awt.SunToolkit.awtLock(SunToolkit.java:229)
at sun.awt.X11.XToolkit.getScreenResolution(XToolkit.java:999)
Run Code Online (Sandbox Code Playgroud)

所以我想要清理的是:

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

lya*_*ffe 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();
 *         }   
 *     }   
 */
Run Code Online (Sandbox Code Playgroud)