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