1 <!doctype html>
   2 <html lang="en">
   3 <head>
   4   <meta charset="utf-8"/>
   5   <title>AWT Threading Issues</title>
   6 </head>
   7 <!--
   8  Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
   9  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  10 
  11  This code is free software; you can redistribute it and/or modify it
  12  under the terms of the GNU General Public License version 2 only, as
  13  published by the Free Software Foundation.  Oracle designates this
  14  particular file as subject to the "Classpath" exception as provided
  15  by Oracle in the LICENSE file that accompanied this code.
  16 
  17  This code is distributed in the hope that it will be useful, but WITHOUT
  18  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  19  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  20  version 2 for more details (a copy is included in the LICENSE file that
  21  accompanied this code).
  22 
  23  You should have received a copy of the GNU General Public License version
  24  2 along with this work; if not, write to the Free Software Foundation,
  25  Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  26 
  27  Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  28  or visit www.oracle.com if you need additional information or have any
  29  questions.
  30 -->
  31 
  32 <body>
  33 
  34 <h1>AWT Threading Issues</h1>
  35 
  36 <a id="ListenersThreads"></a>
  37 <h2>Listeners and threads</h2>
  38 
  39 Unless otherwise noted all AWT listeners are notified on the event
  40 dispatch thread. It is safe to remove/add listeners from any thread
  41 during dispatching, but the changes only effect subsequent notification.
  42 <br>For example, if a key listeners is added from another key listener, the
  43 newly added listener is only notified on subsequent key events.
  44 
  45 <a id="Autoshutdown"></a>
  46 <h2>Auto-shutdown</h2>
  47 
  48 According to
  49 <cite>The Java&trade; Virtual Machine Specification</cite>,
  50 sections 2.17.9 and 2.19,
  51 the Java virtual machine (JVM) initially starts up with a single non-daemon
  52 thread, which typically calls the <code>main</code> method of some class.
  53 The virtual machine terminates all its activity and exits when
  54 one of two things happens:
  55 <ul>
  56   <li> All the threads that are not daemon threads terminate.
  57   <li> Some thread invokes the <code>exit</code> method of class
  58   <code>Runtime</code> or class <code>System</code>, and the exit
  59   operation is permitted by the security manager.
  60 </ul>
  61 <p>
  62 This implies that if an application doesn't start any threads itself,
  63 the JVM will exit as soon as <code>main</code> terminates.
  64 This is not the case, however, for a simple application
  65 that creates and displays a <code>java.awt.Frame</code>:
  66 <pre>
  67         public static void main(String[] args) {
  68             Frame frame = new Frame();
  69             frame.setVisible(true);
  70          }
  71 </pre>
  72 The reason is that AWT encapsulates asynchronous event dispatch
  73 machinery to process events AWT or Swing components can fire. The
  74 exact behavior of this machinery is implementation-dependent. In
  75 particular, it can start non-daemon helper threads for its internal
  76 purposes. In fact, these are the threads that prevent the example
  77 above from exiting. The only restrictions imposed on the behavior of
  78 this machinery are as follows:
  79 <ul>
  80   <li> <a href="../EventQueue.html#isDispatchThread()"><code>EventQueue.isDispatchThread</code></a>
  81        returns <code>true</code> if and only if the calling thread is the
  82        event dispatch thread started by the machinery;
  83   <li> <code>AWTEvents</code> which were actually enqueued to a
  84        particular <code>EventQueue</code> (note that events being
  85        posted to the <code>EventQueue</code> can be coalesced) are
  86        dispatched:
  87        <ul>
  88            <li>
  89            <dl><dt>Sequentially.
  90              <dd> That is, it is not permitted that several events from
  91                 this queue are dispatched simultaneously. </dd></dl>
  92            <li>
  93            <dl><dt>In the same order as they are enqueued.
  94              <dd> That is, if <code>AWTEvent</code>&nbsp;A is enqueued
  95                 to the <code>EventQueue</code> before
  96                 <code>AWTEvent</code>&nbsp;B then event B will not be
  97                 dispatched before event A.</dd></dl>
  98        </ul>
  99   <li> There is at least one alive non-daemon thread while there is at
 100        least one displayable AWT or Swing component within the
 101        application (see
 102        <a href="../Component.html#isDisplayable()"><code>Component.isDisplayable</code></a>).
 103 </ul>
 104 The implications of the third restriction are as follows:
 105 <ul>
 106   <li> The JVM will exit if some thread invokes the <code>exit</code>
 107   method of class <code>Runtime</code> or class <code>System</code>
 108   regardless of the presence of displayable components;
 109   <li> Even if the application terminates all non-daemon threads it
 110   started, the JVM will not exit while there is at least one
 111   displayable component.
 112 </ul>
 113 It depends on the implementation if and when the non-daemon helper
 114 threads are terminated once all components are made undisplayable.
 115 The implementation-specific details are given below.
 116 
 117 <h3>
 118 Implementation-dependent behavior.
 119 </h3>
 120 
 121 Prior to 1.4, the helper threads were never terminated.
 122 <p>
 123 Starting with 1.4, the behavior has changed as a result of the fix for
 124 <a href="http://bugs.sun.com/view_bug.do?bug_id=4030718">
 125 4030718</a>. With the current implementation, AWT terminates all its
 126 helper threads allowing the application to exit cleanly when the
 127 following three conditions are true:
 128 <ul>
 129   <li> There are no displayable AWT or Swing components.
 130   <li> There are no native events in the native event queue.
 131   <li> There are no AWT events in java EventQueues.
 132 </ul>
 133 Therefore, a stand-alone AWT application that wishes to exit
 134 cleanly without calling <code>System.exit</code> must:
 135 <ul>
 136   <li> Make sure that all AWT or Swing components are made
 137        undisplayable when the application finishes. This can be done
 138        by calling
 139 <a href="../Window.html#dispose()"><code>Window.dispose</code></a>
 140        on all top-level <code>Windows</code>. See
 141 <a href="../Frame.html#getFrames()"><code>Frame.getFrames</code></a>.
 142   <li> Make sure that no method of AWT event listeners registered by
 143        the application with any AWT or Swing component can run into an
 144        infinite loop or hang indefinitely. For example, an AWT listener
 145        method triggered by some AWT event can post a new AWT event of
 146        the same type to the <code>EventQueue</code>.
 147        The argument is that methods
 148        of AWT event listeners are typically executed on helper
 149        threads.
 150 </ul>
 151 Note, that while an application following these recommendations will
 152 exit cleanly under normal conditions, it is not guaranteed that it
 153 will exit cleanly in all cases. Two examples:
 154 <ul>
 155   <li> Other packages can create displayable components for internal
 156        needs and never make them undisplayable. See
 157 <a href="http://bugs.sun.com/view_bug.do?bug_id=4515058">
 158 4515058</a>,
 159 <a href="http://bugs.sun.com/view_bug.do?bug_id=4671025">
 160 4671025</a>, and
 161 <a href="http://bugs.sun.com/view_bug.do?bug_id=4465537">
 162 4465537</a>.
 163   <li> Both Microsoft Windows and X11 allow an application to send native
 164        events to windows that belong to another application. With this
 165        feature it is possible to write a malicious program that will
 166        continuously send events to all available windows preventing
 167        any AWT application from exiting cleanly.
 168 </ul>
 169 On the other hand, if you require the JVM to continue running even after
 170 the application has made all components undisplayable you should start a
 171 non-daemon thread that blocks forever.
 172 
 173 <pre>
 174         &lt;...&gt;
 175         Runnable r = new Runnable() {
 176             public void run() {
 177                 Object o = new Object();
 178                 try {
 179                     synchronized (o) {
 180                         o.wait();
 181                     }
 182                 } catch (InterruptedException ie) {
 183                 }
 184             }
 185         };
 186         Thread t = new Thread(r);
 187         t.setDaemon(false);
 188         t.start();
 189         &lt;...&gt;
 190 </pre>
 191 
 192 <cite>The Java&trade; Virtual Machine Specification</cite>
 193  guarantees
 194 that the JVM doesn't exit until this thread terminates.
 195 </body>
 196 </html>