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