1 /*
   2  * Copyright (c) 1998, 2008, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.awt;
  27 
  28 import java.awt.EventQueue;
  29 import java.awt.Window;
  30 import java.awt.SystemTray;
  31 import java.awt.TrayIcon;
  32 import java.awt.Toolkit;
  33 import java.awt.GraphicsEnvironment;
  34 import java.awt.event.InvocationEvent;
  35 import java.security.AccessController;
  36 import java.security.PrivilegedAction;
  37 import java.util.Collections;
  38 import java.util.HashMap;
  39 import java.util.IdentityHashMap;
  40 import java.util.Map;
  41 import java.util.Set;
  42 import java.util.HashSet;
  43 import java.beans.PropertyChangeSupport;
  44 import java.beans.PropertyChangeListener;
  45 import sun.util.logging.PlatformLogger;
  46 import java.util.concurrent.locks.Condition;
  47 import java.util.concurrent.locks.Lock;
  48 import java.util.concurrent.locks.ReentrantLock;
  49 import java.util.concurrent.atomic.AtomicInteger;
  50 
  51 /**
  52  * The AppContext is a table referenced by ThreadGroup which stores
  53  * application service instances.  (If you are not writing an application
  54  * service, or don't know what one is, please do not use this class.)
  55  * The AppContext allows applet access to what would otherwise be
  56  * potentially dangerous services, such as the ability to peek at
  57  * EventQueues or change the look-and-feel of a Swing application.<p>
  58  *
  59  * Most application services use a singleton object to provide their
  60  * services, either as a default (such as getSystemEventQueue or
  61  * getDefaultToolkit) or as static methods with class data (System).
  62  * The AppContext works with the former method by extending the concept
  63  * of "default" to be ThreadGroup-specific.  Application services
  64  * lookup their singleton in the AppContext.<p>
  65  *
  66  * For example, here we have a Foo service, with its pre-AppContext
  67  * code:<p>
  68  * <code><pre>
  69  *    public class Foo {
  70  *        private static Foo defaultFoo = new Foo();
  71  *
  72  *        public static Foo getDefaultFoo() {
  73  *            return defaultFoo;
  74  *        }
  75  *
  76  *    ... Foo service methods
  77  *    }</pre></code><p>
  78  *
  79  * The problem with the above is that the Foo service is global in scope,
  80  * so that applets and other untrusted code can execute methods on the
  81  * single, shared Foo instance.  The Foo service therefore either needs
  82  * to block its use by untrusted code using a SecurityManager test, or
  83  * restrict its capabilities so that it doesn't matter if untrusted code
  84  * executes it.<p>
  85  *
  86  * Here's the Foo class written to use the AppContext:<p>
  87  * <code><pre>
  88  *    public class Foo {
  89  *        public static Foo getDefaultFoo() {
  90  *            Foo foo = (Foo)AppContext.getAppContext().get(Foo.class);
  91  *            if (foo == null) {
  92  *                foo = new Foo();
  93  *                getAppContext().put(Foo.class, foo);
  94  *            }
  95  *            return foo;
  96  *        }
  97  *
  98  *    ... Foo service methods
  99  *    }</pre></code><p>
 100  *
 101  * Since a separate AppContext can exist for each ThreadGroup, trusted
 102  * and untrusted code have access to different Foo instances.  This allows
 103  * untrusted code access to "system-wide" services -- the service remains
 104  * within the AppContext "sandbox".  For example, say a malicious applet
 105  * wants to peek all of the key events on the EventQueue to listen for
 106  * passwords; if separate EventQueues are used for each ThreadGroup
 107  * using AppContexts, the only key events that applet will be able to
 108  * listen to are its own.  A more reasonable applet request would be to
 109  * change the Swing default look-and-feel; with that default stored in
 110  * an AppContext, the applet's look-and-feel will change without
 111  * disrupting other applets or potentially the browser itself.<p>
 112  *
 113  * Because the AppContext is a facility for safely extending application
 114  * service support to applets, none of its methods may be blocked by a
 115  * a SecurityManager check in a valid Java implementation.  Applets may
 116  * therefore safely invoke any of its methods without worry of being
 117  * blocked.
 118  *
 119  * Note: If a SecurityManager is installed which derives from
 120  * sun.awt.AWTSecurityManager, it may override the
 121  * AWTSecurityManager.getAppContext() method to return the proper
 122  * AppContext based on the execution context, in the case where
 123  * the default ThreadGroup-based AppContext indexing would return
 124  * the main "system" AppContext.  For example, in an applet situation,
 125  * if a system thread calls into an applet, rather than returning the
 126  * main "system" AppContext (the one corresponding to the system thread),
 127  * an installed AWTSecurityManager may return the applet's AppContext
 128  * based on the execution context.
 129  *
 130  * @author  Thomas Ball
 131  * @author  Fred Ecks
 132  */
 133 public final class AppContext {
 134     private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.AppContext");
 135 
 136     /* Since the contents of an AppContext are unique to each Java
 137      * session, this class should never be serialized. */
 138 
 139     /*
 140      * The key to put()/get() the Java EventQueue into/from the AppContext.
 141      */
 142     public static final Object EVENT_QUEUE_KEY = new StringBuffer("EventQueue");
 143 
 144     /*
 145      * The keys to store EventQueue push/pop lock and condition.
 146      */
 147     public final static Object EVENT_QUEUE_LOCK_KEY = new StringBuilder("EventQueue.Lock");
 148     public final static Object EVENT_QUEUE_COND_KEY = new StringBuilder("EventQueue.Condition");
 149 
 150     /* A map of AppContexts, referenced by ThreadGroup.
 151      */
 152     private static final Map<ThreadGroup, AppContext> threadGroup2appContext =
 153             Collections.synchronizedMap(new IdentityHashMap<ThreadGroup, AppContext>());
 154 
 155     /**
 156      * Returns a set containing all <code>AppContext</code>s.
 157      */
 158     public static Set<AppContext> getAppContexts() {
 159         synchronized (threadGroup2appContext) {
 160             return new HashSet<AppContext>(threadGroup2appContext.values());
 161         }
 162     }
 163 
 164     /* The main "system" AppContext, used by everything not otherwise
 165        contained in another AppContext. It is implicitly created for
 166        standalone apps only (i.e. not applets)
 167      */
 168     private static volatile AppContext mainAppContext = null;
 169 
 170     private static class GetAppContextLock {};
 171     private final static Object getAppContextLock = new GetAppContextLock();
 172 
 173     /*
 174      * The hash map associated with this AppContext.  A private delegate
 175      * is used instead of subclassing HashMap so as to avoid all of
 176      * HashMap's potentially risky methods, such as clear(), elements(),
 177      * putAll(), etc.
 178      */
 179     private final Map<Object, Object> table = new HashMap<>();
 180 
 181     private final ThreadGroup threadGroup;
 182 
 183     /**
 184      * If any <code>PropertyChangeListeners</code> have been registered,
 185      * the <code>changeSupport</code> field describes them.
 186      *
 187      * @see #addPropertyChangeListener
 188      * @see #removePropertyChangeListener
 189      * @see #firePropertyChange
 190      */
 191     private PropertyChangeSupport changeSupport = null;
 192 
 193     public static final String DISPOSED_PROPERTY_NAME = "disposed";
 194     public static final String GUI_DISPOSED = "guidisposed";
 195 
 196     private enum State {
 197         VALID,
 198         BEING_DISPOSED,
 199         DISPOSED
 200     };
 201 
 202     private volatile State state = State.VALID;
 203 
 204     public boolean isDisposed() {
 205         return state == State.DISPOSED;
 206     }
 207 
 208     /*
 209      * The total number of AppContexts, system-wide.  This number is
 210      * incremented at the beginning of the constructor, and decremented
 211      * at the end of dispose().  getAppContext() checks to see if this
 212      * number is 1.  If so, it returns the sole AppContext without
 213      * checking Thread.currentThread().
 214      */
 215     private static final AtomicInteger numAppContexts = new AtomicInteger(0);
 216 
 217 
 218     /*
 219      * The context ClassLoader that was used to create this AppContext.
 220      */
 221     private final ClassLoader contextClassLoader;
 222 
 223     /**
 224      * Constructor for AppContext.  This method is <i>not</i> public,
 225      * nor should it ever be used as such.  The proper way to construct
 226      * an AppContext is through the use of SunToolkit.createNewAppContext.
 227      * A ThreadGroup is created for the new AppContext, a Thread is
 228      * created within that ThreadGroup, and that Thread calls
 229      * SunToolkit.createNewAppContext before calling anything else.
 230      * That creates both the new AppContext and its EventQueue.
 231      *
 232      * @param   threadGroup     The ThreadGroup for the new AppContext
 233      * @see     sun.awt.SunToolkit
 234      * @since   1.2
 235      */
 236     AppContext(ThreadGroup threadGroup) {
 237         numAppContexts.incrementAndGet();
 238 
 239         this.threadGroup = threadGroup;
 240         threadGroup2appContext.put(threadGroup, this);
 241 
 242         this.contextClassLoader =
 243              AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
 244                     public ClassLoader run() {
 245                         return Thread.currentThread().getContextClassLoader();
 246                     }
 247                 });
 248 
 249         // Initialize push/pop lock and its condition to be used by all the
 250         // EventQueues within this AppContext
 251         Lock eventQueuePushPopLock = new ReentrantLock();
 252         put(EVENT_QUEUE_LOCK_KEY, eventQueuePushPopLock);
 253         Condition eventQueuePushPopCond = eventQueuePushPopLock.newCondition();
 254         put(EVENT_QUEUE_COND_KEY, eventQueuePushPopCond);
 255     }
 256 
 257     private static final ThreadLocal<AppContext> threadAppContext =
 258             new ThreadLocal<AppContext>();
 259 
 260     private final static void initMainAppContext() {
 261         // On the main Thread, we get the ThreadGroup, make a corresponding
 262         // AppContext, and instantiate the Java EventQueue.  This way, legacy
 263         // code is unaffected by the move to multiple AppContext ability.
 264         AccessController.doPrivileged(new PrivilegedAction<Void>() {
 265             public Void run() {
 266                 ThreadGroup currentThreadGroup =
 267                         Thread.currentThread().getThreadGroup();
 268                 ThreadGroup parentThreadGroup = currentThreadGroup.getParent();
 269                 while (parentThreadGroup != null) {
 270                     // Find the root ThreadGroup to construct our main AppContext
 271                     currentThreadGroup = parentThreadGroup;
 272                     parentThreadGroup = currentThreadGroup.getParent();
 273                 }
 274 
 275                 mainAppContext = SunToolkit.createNewAppContext(currentThreadGroup);
 276                 return null;
 277             }
 278         });
 279     }
 280 
 281     /**
 282      * Returns the appropriate AppContext for the caller,
 283      * as determined by its ThreadGroup.  If the main "system" AppContext
 284      * would be returned and there's an AWTSecurityManager installed, it
 285      * is called to get the proper AppContext based on the execution
 286      * context.
 287      *
 288      * @return  the AppContext for the caller.
 289      * @see     java.lang.ThreadGroup
 290      * @since   1.2
 291      */
 292     public final static AppContext getAppContext() {
 293         // we are standalone app, return the main app context
 294         if (numAppContexts.get() == 1 && mainAppContext != null) {
 295             return mainAppContext;
 296         }
 297 
 298         AppContext appContext = threadAppContext.get();
 299 
 300         if (null == appContext) {
 301             appContext = AccessController.doPrivileged(new PrivilegedAction<AppContext>()
 302             {
 303                 public AppContext run() {
 304                     // Get the current ThreadGroup, and look for it and its
 305                     // parents in the hash from ThreadGroup to AppContext --
 306                     // it should be found, because we use createNewContext()
 307                     // when new AppContext objects are created.
 308                     ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup();
 309                     ThreadGroup threadGroup = currentThreadGroup;
 310 
 311                     // Special case: we implicitly create the main app context
 312                     // if no contexts have been created yet. This covers standalone apps
 313                     // and excludes applets because by the time applet starts
 314                     // a number of contexts have already been created by the plugin.
 315                     synchronized (getAppContextLock) {
 316                         if (numAppContexts.get() == 0) {
 317                             if (System.getProperty("javaplugin.version") == null &&
 318                                     System.getProperty("javawebstart.version") == null) {
 319                                 initMainAppContext();
 320                             } else if (System.getProperty("javafx.version") != null &&
 321                                     threadGroup.getParent() != null) {
 322                                 // Swing inside JavaFX case
 323                                 SunToolkit.createNewAppContext();
 324                             }
 325                         }
 326                     }
 327 
 328                     AppContext context = threadGroup2appContext.get(threadGroup);
 329                     while (context == null) {
 330                         threadGroup = threadGroup.getParent();
 331                         if (threadGroup == null) {
 332                             return null;
 333                         }
 334                         context = threadGroup2appContext.get(threadGroup);
 335                     }
 336 
 337                     // In case we did anything in the above while loop, we add
 338                     // all the intermediate ThreadGroups to threadGroup2appContext
 339                     // so we won't spin again.
 340                     for (ThreadGroup tg = currentThreadGroup; tg != threadGroup; tg = tg.getParent()) {
 341                         threadGroup2appContext.put(tg, context);
 342                     }
 343 
 344                     // Now we're done, so we cache the latest key/value pair.
 345                     threadAppContext.set(context);
 346 
 347                     return context;
 348                 }
 349             });
 350         }
 351 
 352         return appContext;
 353     }
 354 
 355     /**
 356      * Returns true if the specified AppContext is the main AppContext.
 357      *
 358      * @param   ctx the context to compare with the main context
 359      * @return  true if the specified AppContext is the main AppContext.
 360      * @since   1.8
 361      */
 362     public final static boolean isMainContext(AppContext ctx) {
 363         return (ctx != null && ctx == mainAppContext);
 364     }
 365 
 366     private final static AppContext getExecutionAppContext() {
 367         SecurityManager securityManager = System.getSecurityManager();
 368         if ((securityManager != null) &&
 369             (securityManager instanceof AWTSecurityManager))
 370         {
 371             AWTSecurityManager awtSecMgr = (AWTSecurityManager) securityManager;
 372             AppContext secAppContext = awtSecMgr.getAppContext();
 373             return secAppContext; // Return what we're told
 374         }
 375         return null;
 376     }
 377 
 378     private long DISPOSAL_TIMEOUT = 5000;  // Default to 5-second timeout
 379                                            // for disposal of all Frames
 380                                            // (we wait for this time twice,
 381                                            // once for dispose(), and once
 382                                            // to clear the EventQueue).
 383 
 384     private long THREAD_INTERRUPT_TIMEOUT = 1000;
 385                             // Default to 1-second timeout for all
 386                             // interrupted Threads to exit, and another
 387                             // 1 second for all stopped Threads to die.
 388 
 389     /**
 390      * Disposes of this AppContext, all of its top-level Frames, and
 391      * all Threads and ThreadGroups contained within it.
 392      *
 393      * This method must be called from a Thread which is not contained
 394      * within this AppContext.
 395      *
 396      * @exception  IllegalThreadStateException  if the current thread is
 397      *                                    contained within this AppContext
 398      * @since      1.2
 399      */
 400     public void dispose() throws IllegalThreadStateException {
 401         // Check to be sure that the current Thread isn't in this AppContext
 402         if (this.threadGroup.parentOf(Thread.currentThread().getThreadGroup())) {
 403             throw new IllegalThreadStateException(
 404                 "Current Thread is contained within AppContext to be disposed."
 405               );
 406         }
 407 
 408         synchronized(this) {
 409             if (this.state != State.VALID) {
 410                 return; // If already disposed or being disposed, bail.
 411             }
 412 
 413             this.state = State.BEING_DISPOSED;
 414         }
 415 
 416         final PropertyChangeSupport changeSupport = this.changeSupport;
 417         if (changeSupport != null) {
 418             changeSupport.firePropertyChange(DISPOSED_PROPERTY_NAME, false, true);
 419         }
 420 
 421         // First, we post an InvocationEvent to be run on the
 422         // EventDispatchThread which disposes of all top-level Frames and TrayIcons
 423 
 424         final Object notificationLock = new Object();
 425 
 426         Runnable runnable = new Runnable() {
 427             public void run() {
 428                 Window[] windowsToDispose = Window.getOwnerlessWindows();
 429                 for (Window w : windowsToDispose) {
 430                     try {
 431                         w.dispose();
 432                     } catch (Throwable t) {
 433                         log.finer("exception occured while disposing app context", t);
 434                     }
 435                 }
 436                 AccessController.doPrivileged(new PrivilegedAction<Void>() {
 437                         public Void run() {
 438                             if (!GraphicsEnvironment.isHeadless() && SystemTray.isSupported())
 439                             {
 440                                 SystemTray systemTray = SystemTray.getSystemTray();
 441                                 TrayIcon[] trayIconsToDispose = systemTray.getTrayIcons();
 442                                 for (TrayIcon ti : trayIconsToDispose) {
 443                                     systemTray.remove(ti);
 444                                 }
 445                             }
 446                             return null;
 447                         }
 448                     });
 449                 // Alert PropertyChangeListeners that the GUI has been disposed.
 450                 if (changeSupport != null) {
 451                     changeSupport.firePropertyChange(GUI_DISPOSED, false, true);
 452                 }
 453                 synchronized(notificationLock) {
 454                     notificationLock.notifyAll(); // Notify caller that we're done
 455                 }
 456             }
 457         };
 458         synchronized(notificationLock) {
 459             SunToolkit.postEvent(this,
 460                 new InvocationEvent(Toolkit.getDefaultToolkit(), runnable));
 461             try {
 462                 notificationLock.wait(DISPOSAL_TIMEOUT);
 463             } catch (InterruptedException e) { }
 464         }
 465 
 466         // Next, we post another InvocationEvent to the end of the
 467         // EventQueue.  When it's executed, we know we've executed all
 468         // events in the queue.
 469 
 470         runnable = new Runnable() { public void run() {
 471             synchronized(notificationLock) {
 472                 notificationLock.notifyAll(); // Notify caller that we're done
 473             }
 474         } };
 475         synchronized(notificationLock) {
 476             SunToolkit.postEvent(this,
 477                 new InvocationEvent(Toolkit.getDefaultToolkit(), runnable));
 478             try {
 479                 notificationLock.wait(DISPOSAL_TIMEOUT);
 480             } catch (InterruptedException e) { }
 481         }
 482 
 483         // We are done with posting events, so change the state to disposed
 484         synchronized(this) {
 485             this.state = State.DISPOSED;
 486         }
 487 
 488         // Next, we interrupt all Threads in the ThreadGroup
 489         this.threadGroup.interrupt();
 490             // Note, the EventDispatchThread we've interrupted may dump an
 491             // InterruptedException to the console here.  This needs to be
 492             // fixed in the EventDispatchThread, not here.
 493 
 494         // Next, we sleep 10ms at a time, waiting for all of the active
 495         // Threads in the ThreadGroup to exit.
 496 
 497         long startTime = System.currentTimeMillis();
 498         long endTime = startTime + THREAD_INTERRUPT_TIMEOUT;
 499         while ((this.threadGroup.activeCount() > 0) &&
 500                (System.currentTimeMillis() < endTime)) {
 501             try {
 502                 Thread.sleep(10);
 503             } catch (InterruptedException e) { }
 504         }
 505 
 506         // Then, we stop any remaining Threads
 507         this.threadGroup.stop();
 508 
 509         // Next, we sleep 10ms at a time, waiting for all of the active
 510         // Threads in the ThreadGroup to die.
 511 
 512         startTime = System.currentTimeMillis();
 513         endTime = startTime + THREAD_INTERRUPT_TIMEOUT;
 514         while ((this.threadGroup.activeCount() > 0) &&
 515                (System.currentTimeMillis() < endTime)) {
 516             try {
 517                 Thread.sleep(10);
 518             } catch (InterruptedException e) { }
 519         }
 520 
 521         // Next, we remove this and all subThreadGroups from threadGroup2appContext
 522         int numSubGroups = this.threadGroup.activeGroupCount();
 523         if (numSubGroups > 0) {
 524             ThreadGroup [] subGroups = new ThreadGroup[numSubGroups];
 525             numSubGroups = this.threadGroup.enumerate(subGroups);
 526             for (int subGroup = 0; subGroup < numSubGroups; subGroup++) {
 527                 threadGroup2appContext.remove(subGroups[subGroup]);
 528             }
 529         }
 530         threadGroup2appContext.remove(this.threadGroup);
 531 
 532         threadAppContext.set(null);
 533 
 534         // Finally, we destroy the ThreadGroup entirely.
 535         try {
 536             this.threadGroup.destroy();
 537         } catch (IllegalThreadStateException e) {
 538             // Fired if not all the Threads died, ignore it and proceed
 539         }
 540 
 541         synchronized (table) {
 542             this.table.clear(); // Clear out the Hashtable to ease garbage collection
 543         }
 544 
 545         numAppContexts.decrementAndGet();
 546 
 547         mostRecentKeyValue = null;
 548     }
 549 
 550     static final class PostShutdownEventRunnable implements Runnable {
 551         private final AppContext appContext;
 552 
 553         public PostShutdownEventRunnable(AppContext ac) {
 554             appContext = ac;
 555         }
 556 
 557         public void run() {
 558             final EventQueue eq = (EventQueue)appContext.get(EVENT_QUEUE_KEY);
 559             if (eq != null) {
 560                 eq.postEvent(AWTAutoShutdown.getShutdownEvent());
 561             }
 562         }
 563     }
 564 
 565     static final class CreateThreadAction implements PrivilegedAction<Thread> {
 566         private final AppContext appContext;
 567         private final Runnable runnable;
 568 
 569         public CreateThreadAction(AppContext ac, Runnable r) {
 570             appContext = ac;
 571             runnable = r;
 572         }
 573 
 574         public Thread run() {
 575             Thread t = new Thread(appContext.getThreadGroup(), runnable);
 576             t.setContextClassLoader(appContext.getContextClassLoader());
 577             t.setPriority(Thread.NORM_PRIORITY + 1);
 578             t.setDaemon(true);
 579             return t;
 580         }
 581     }
 582 
 583     static void stopEventDispatchThreads() {
 584         for (AppContext appContext: getAppContexts()) {
 585             if (appContext.isDisposed()) {
 586                 continue;
 587             }
 588             Runnable r = new PostShutdownEventRunnable(appContext);
 589             // For security reasons EventQueue.postEvent should only be called
 590             // on a thread that belongs to the corresponding thread group.
 591             if (appContext != AppContext.getAppContext()) {
 592                 // Create a thread that belongs to the thread group associated
 593                 // with the AppContext and invokes EventQueue.postEvent.
 594                 PrivilegedAction<Thread> action = new CreateThreadAction(appContext, r);
 595                 Thread thread = AccessController.doPrivileged(action);
 596                 thread.start();
 597             } else {
 598                 r.run();
 599             }
 600         }
 601     }
 602 
 603     private MostRecentKeyValue mostRecentKeyValue = null;
 604     private MostRecentKeyValue shadowMostRecentKeyValue = null;
 605 
 606     /**
 607      * Returns the value to which the specified key is mapped in this context.
 608      *
 609      * @param   key   a key in the AppContext.
 610      * @return  the value to which the key is mapped in this AppContext;
 611      *          <code>null</code> if the key is not mapped to any value.
 612      * @see     #put(Object, Object)
 613      * @since   1.2
 614      */
 615     public Object get(Object key) {
 616         /*
 617          * The most recent reference should be updated inside a synchronized
 618          * block to avoid a race when put() and get() are executed in
 619          * parallel on different threads.
 620          */
 621         synchronized (table) {
 622             // Note: this most recent key/value caching is thread-hot.
 623             // A simple test using SwingSet found that 72% of lookups
 624             // were matched using the most recent key/value.  By instantiating
 625             // a simple MostRecentKeyValue object on cache misses, the
 626             // cache hits can be processed without synchronization.
 627 
 628             MostRecentKeyValue recent = mostRecentKeyValue;
 629             if ((recent != null) && (recent.key == key)) {
 630                 return recent.value;
 631             }
 632 
 633             Object value = table.get(key);
 634             if(mostRecentKeyValue == null) {
 635                 mostRecentKeyValue = new MostRecentKeyValue(key, value);
 636                 shadowMostRecentKeyValue = new MostRecentKeyValue(key, value);
 637             } else {
 638                 MostRecentKeyValue auxKeyValue = mostRecentKeyValue;
 639                 shadowMostRecentKeyValue.setPair(key, value);
 640                 mostRecentKeyValue = shadowMostRecentKeyValue;
 641                 shadowMostRecentKeyValue = auxKeyValue;
 642             }
 643             return value;
 644         }
 645     }
 646 
 647     /**
 648      * Maps the specified <code>key</code> to the specified
 649      * <code>value</code> in this AppContext.  Neither the key nor the
 650      * value can be <code>null</code>.
 651      * <p>
 652      * The value can be retrieved by calling the <code>get</code> method
 653      * with a key that is equal to the original key.
 654      *
 655      * @param      key     the AppContext key.
 656      * @param      value   the value.
 657      * @return     the previous value of the specified key in this
 658      *             AppContext, or <code>null</code> if it did not have one.
 659      * @exception  NullPointerException  if the key or value is
 660      *               <code>null</code>.
 661      * @see     #get(Object)
 662      * @since   1.2
 663      */
 664     public Object put(Object key, Object value) {
 665         synchronized (table) {
 666             MostRecentKeyValue recent = mostRecentKeyValue;
 667             if ((recent != null) && (recent.key == key))
 668                 recent.value = value;
 669             return table.put(key, value);
 670         }
 671     }
 672 
 673     /**
 674      * Removes the key (and its corresponding value) from this
 675      * AppContext. This method does nothing if the key is not in the
 676      * AppContext.
 677      *
 678      * @param   key   the key that needs to be removed.
 679      * @return  the value to which the key had been mapped in this AppContext,
 680      *          or <code>null</code> if the key did not have a mapping.
 681      * @since   1.2
 682      */
 683     public Object remove(Object key) {
 684         synchronized (table) {
 685             MostRecentKeyValue recent = mostRecentKeyValue;
 686             if ((recent != null) && (recent.key == key))
 687                 recent.value = null;
 688             return table.remove(key);
 689         }
 690     }
 691 
 692     /**
 693      * Returns the root ThreadGroup for all Threads contained within
 694      * this AppContext.
 695      * @since   1.2
 696      */
 697     public ThreadGroup getThreadGroup() {
 698         return threadGroup;
 699     }
 700 
 701     /**
 702      * Returns the context ClassLoader that was used to create this
 703      * AppContext.
 704      *
 705      * @see java.lang.Thread#getContextClassLoader
 706      */
 707     public ClassLoader getContextClassLoader() {
 708         return contextClassLoader;
 709     }
 710 
 711     /**
 712      * Returns a string representation of this AppContext.
 713      * @since   1.2
 714      */
 715     @Override
 716     public String toString() {
 717         return getClass().getName() + "[threadGroup=" + threadGroup.getName() + "]";
 718     }
 719 
 720     /**
 721      * Returns an array of all the property change listeners
 722      * registered on this component.
 723      *
 724      * @return all of this component's <code>PropertyChangeListener</code>s
 725      *         or an empty array if no property change
 726      *         listeners are currently registered
 727      *
 728      * @see      #addPropertyChangeListener
 729      * @see      #removePropertyChangeListener
 730      * @see      #getPropertyChangeListeners(java.lang.String)
 731      * @see      java.beans.PropertyChangeSupport#getPropertyChangeListeners
 732      * @since    1.4
 733      */
 734     public synchronized PropertyChangeListener[] getPropertyChangeListeners() {
 735         if (changeSupport == null) {
 736             return new PropertyChangeListener[0];
 737         }
 738         return changeSupport.getPropertyChangeListeners();
 739     }
 740 
 741     /**
 742      * Adds a PropertyChangeListener to the listener list for a specific
 743      * property. The specified property may be one of the following:
 744      * <ul>
 745      *    <li>if this AppContext is disposed ("disposed")</li>
 746      * </ul>
 747      * <ul>
 748      *    <li>if this AppContext's unowned Windows have been disposed
 749      *    ("guidisposed").  Code to cleanup after the GUI is disposed
 750      *    (such as LookAndFeel.uninitialize()) should execute in response to
 751      *    this property being fired.  Notifications for the "guidisposed"
 752      *    property are sent on the event dispatch thread.</li>
 753      * </ul>
 754      * <p>
 755      * If listener is null, no exception is thrown and no action is performed.
 756      *
 757      * @param propertyName one of the property names listed above
 758      * @param listener the PropertyChangeListener to be added
 759      *
 760      * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
 761      * @see #getPropertyChangeListeners(java.lang.String)
 762      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
 763      */
 764     public synchronized void addPropertyChangeListener(
 765                              String propertyName,
 766                              PropertyChangeListener listener) {
 767         if (listener == null) {
 768             return;
 769         }
 770         if (changeSupport == null) {
 771             changeSupport = new PropertyChangeSupport(this);
 772         }
 773         changeSupport.addPropertyChangeListener(propertyName, listener);
 774     }
 775 
 776     /**
 777      * Removes a PropertyChangeListener from the listener list for a specific
 778      * property. This method should be used to remove PropertyChangeListeners
 779      * that were registered for a specific bound property.
 780      * <p>
 781      * If listener is null, no exception is thrown and no action is performed.
 782      *
 783      * @param propertyName a valid property name
 784      * @param listener the PropertyChangeListener to be removed
 785      *
 786      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
 787      * @see #getPropertyChangeListeners(java.lang.String)
 788      * @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
 789      */
 790     public synchronized void removePropertyChangeListener(
 791                              String propertyName,
 792                              PropertyChangeListener listener) {
 793         if (listener == null || changeSupport == null) {
 794             return;
 795         }
 796         changeSupport.removePropertyChangeListener(propertyName, listener);
 797     }
 798 
 799     /**
 800      * Returns an array of all the listeners which have been associated
 801      * with the named property.
 802      *
 803      * @return all of the <code>PropertyChangeListeners</code> associated with
 804      *         the named property or an empty array if no listeners have
 805      *         been added
 806      *
 807      * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
 808      * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
 809      * @see #getPropertyChangeListeners
 810      * @since 1.4
 811      */
 812     public synchronized PropertyChangeListener[] getPropertyChangeListeners(
 813                                                         String propertyName) {
 814         if (changeSupport == null) {
 815             return new PropertyChangeListener[0];
 816         }
 817         return changeSupport.getPropertyChangeListeners(propertyName);
 818     }
 819 
 820     // Set up JavaAWTAccess in SharedSecrets
 821     static {
 822         sun.misc.SharedSecrets.setJavaAWTAccess(new sun.misc.JavaAWTAccess() {
 823             public Object get(Object key) {
 824                 AppContext ac = getAppContext();
 825                 return (ac == null) ? null : ac.get(key);
 826             }
 827             public void put(Object key, Object value) {
 828                 AppContext ac = getAppContext();
 829                 if (ac != null) {
 830                     ac.put(key, value);
 831                 }
 832             }
 833             public void remove(Object key) {
 834                 AppContext ac = getAppContext();
 835                 if (ac != null) {
 836                     ac.remove(key);
 837                 }
 838             }
 839             public boolean isDisposed() {
 840                 AppContext ac = getAppContext();
 841                 return (ac == null) ? true : ac.isDisposed();
 842             }
 843             public boolean isMainAppContext() {
 844                 return (numAppContexts.get() == 1 && mainAppContext != null);
 845             }
 846 
 847             private boolean hasRootThreadGroup(final AppContext ecx) {
 848                 return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
 849                     @Override
 850                     public Boolean run() {
 851                         return ecx.threadGroup.getParent() == null;
 852                     }
 853                 });
 854             }
 855 
 856             /**
 857              * Returns the AppContext used for applet logging isolation, or null if
 858              * the default global context can be used.
 859              * If there's no applet, or if the caller is a stand alone application,
 860              * or running in the main app context, returns null.
 861              * Otherwise, returns the AppContext of the calling applet.
 862              * @return null if the global default context can be used,
 863              *         an AppContext otherwise.
 864              **/
 865             public Object getAppletContext() {
 866                 // There's no AppContext: return null.
 867                 // No need to call getAppContext() if numAppContext == 0:
 868                 // it means that no AppContext has been created yet, and
 869                 // we don't want to trigger the creation of a main app
 870                 // context since we don't need it.
 871                 if (numAppContexts.get() == 0) return null;
 872 
 873                 // Get the context from the security manager
 874                 AppContext ecx = getExecutionAppContext();
 875 
 876                 // Not sure we really need to re-check numAppContexts here.
 877                 // If all applets have gone away then we could have a
 878                 // numAppContexts coming back to 0. So we recheck
 879                 // it here because we don't want to trigger the
 880                 // creation of a main AppContext in that case.
 881                 // This is probably not 100% MT-safe but should reduce
 882                 // the window of opportunity in which that issue could
 883                 // happen.
 884                 if (numAppContexts.get() > 0) {
 885                    // Defaults to thread group caching.
 886                    // This is probably not required as we only really need
 887                    // isolation in a deployed applet environment, in which
 888                    // case ecx will not be null when we reach here
 889                    // However it helps emulate the deployed environment,
 890                    // in tests for instance.
 891                    ecx = ecx != null ? ecx : getAppContext();
 892                 }
 893 
 894                 // getAppletContext() may be called when initializing the main
 895                 // app context - in which case mainAppContext will still be
 896                 // null. To work around this issue we simply use
 897                 // AppContext.threadGroup.getParent() == null instead, since
 898                 // mainAppContext is the only AppContext which should have
 899                 // the root TG as its thread group.
 900                 // See: JDK-8023258
 901                 final boolean isMainAppContext = ecx == null
 902                     || mainAppContext == ecx
 903                     || mainAppContext == null && hasRootThreadGroup(ecx);
 904 
 905                 return isMainAppContext ? null : ecx;
 906             }
 907 
 908         });
 909     }
 910 }
 911 
 912 final class MostRecentKeyValue {
 913     Object key;
 914     Object value;
 915     MostRecentKeyValue(Object k, Object v) {
 916         key = k;
 917         value = v;
 918     }
 919     void setPair(Object k, Object v) {
 920         key = k;
 921         value = v;
 922     }
 923 }