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 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 /* 171 * The hash map associated with this AppContext. A private delegate 172 * is used instead of subclassing HashMap so as to avoid all of 173 * HashMap's potentially risky methods, such as clear(), elements(), 174 * putAll(), etc. 175 */ 176 private final HashMap table = new HashMap(); 177 178 private final ThreadGroup threadGroup; 179 180 /** 181 * If any <code>PropertyChangeListeners</code> have been registered, 182 * the <code>changeSupport</code> field describes them. 183 * 184 * @see #addPropertyChangeListener 185 * @see #removePropertyChangeListener 186 * @see #firePropertyChange 187 */ 188 private PropertyChangeSupport changeSupport = null; 189 190 public static final String DISPOSED_PROPERTY_NAME = "disposed"; 191 public static final String GUI_DISPOSED = "guidisposed"; 192 193 private enum State { 194 VALID, 195 BEING_DISPOSED, 196 DISPOSED 197 }; 198 199 private volatile State state = State.VALID; 200 201 public boolean isDisposed() { 202 return state == State.DISPOSED; 203 } 204 205 /* 206 * The total number of AppContexts, system-wide. This number is 207 * incremented at the beginning of the constructor, and decremented 208 * at the end of dispose(). getAppContext() checks to see if this 209 * number is 1. If so, it returns the sole AppContext without 210 * checking Thread.currentThread(). 211 */ 212 private static final AtomicInteger numAppContexts = new AtomicInteger(0); 213 214 /* 215 * The context ClassLoader that was used to create this AppContext. 216 */ 217 private final ClassLoader contextClassLoader; 218 219 /** 220 * Constructor for AppContext. This method is <i>not</i> public, 221 * nor should it ever be used as such. The proper way to construct 222 * an AppContext is through the use of SunToolkit.createNewAppContext. 223 * A ThreadGroup is created for the new AppContext, a Thread is 224 * created within that ThreadGroup, and that Thread calls 225 * SunToolkit.createNewAppContext before calling anything else. 226 * That creates both the new AppContext and its EventQueue. 227 * 228 * @param threadGroup The ThreadGroup for the new AppContext 229 * @see sun.awt.SunToolkit 230 * @since 1.2 231 */ 232 AppContext(ThreadGroup threadGroup) { 233 numAppContexts.incrementAndGet(); 234 235 this.threadGroup = threadGroup; 236 threadGroup2appContext.put(threadGroup, this); 237 238 this.contextClassLoader = 239 AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { 240 public ClassLoader run() { 241 return Thread.currentThread().getContextClassLoader(); 242 } 243 }); 244 245 // Initialize push/pop lock and its condition to be used by all the 246 // EventQueues within this AppContext 247 Lock eventQueuePushPopLock = new ReentrantLock(); 248 put(EVENT_QUEUE_LOCK_KEY, eventQueuePushPopLock); 249 Condition eventQueuePushPopCond = eventQueuePushPopLock.newCondition(); 250 put(EVENT_QUEUE_COND_KEY, eventQueuePushPopCond); 251 } 252 253 private static final ThreadLocal<AppContext> threadAppContext = 254 new ThreadLocal<AppContext>(); 255 256 private final static void initMainAppContext() { 257 // On the main Thread, we get the ThreadGroup, make a corresponding 258 // AppContext, and instantiate the Java EventQueue. This way, legacy 259 // code is unaffected by the move to multiple AppContext ability. 260 AccessController.doPrivileged(new PrivilegedAction<Void>() { 261 public Void run() { 262 ThreadGroup currentThreadGroup = 263 Thread.currentThread().getThreadGroup(); 264 ThreadGroup parentThreadGroup = currentThreadGroup.getParent(); 265 while (parentThreadGroup != null) { 266 // Find the root ThreadGroup to construct our main AppContext 267 currentThreadGroup = parentThreadGroup; 268 parentThreadGroup = currentThreadGroup.getParent(); 269 } 270 271 mainAppContext = SunToolkit.createNewAppContext(currentThreadGroup); 272 return null; 273 } 274 }); 275 } 276 277 /** 278 * Returns the appropriate AppContext for the caller, 279 * as determined by its ThreadGroup. If the main "system" AppContext 280 * would be returned and there's an AWTSecurityManager installed, it 281 * is called to get the proper AppContext based on the execution 282 * context. 283 * 284 * @return the AppContext for the caller. 285 * @see java.lang.ThreadGroup 286 * @since 1.2 287 */ 288 public final static AppContext getAppContext() { 289 // we are standalone app, return the main app context 290 if (numAppContexts.get() == 1 && mainAppContext != null) { 291 return mainAppContext; 292 } 293 294 AppContext appContext = threadAppContext.get(); 295 296 if (null == appContext) { 297 appContext = AccessController.doPrivileged(new PrivilegedAction<AppContext>() 298 { 299 public AppContext run() { 300 // Get the current ThreadGroup, and look for it and its 301 // parents in the hash from ThreadGroup to AppContext -- 302 // it should be found, because we use createNewContext() 303 // when new AppContext objects are created. 304 ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup(); 305 ThreadGroup threadGroup = currentThreadGroup; 306 307 // Special case: we implicitly create the main app context 308 // if no contexts have been created yet. This covers standalone apps 309 // and excludes applets because by the time applet starts 310 // a number of contexts have already been created by the plugin. 311 if (numAppContexts.get() == 0) { 312 // This check is not necessary, its purpose is to help 313 // Plugin devs to catch all the cases of main AC creation. 314 if (System.getProperty("javaplugin.version") == null && 315 System.getProperty("javawebstart.version") == null) { 316 initMainAppContext(); 317 } 318 } 319 320 AppContext context = threadGroup2appContext.get(threadGroup); 321 while (context == null) { 322 threadGroup = threadGroup.getParent(); 323 if (threadGroup == null) { 324 return null; 325 } 326 context = threadGroup2appContext.get(threadGroup); 327 } 328 329 // In case we did anything in the above while loop, we add 330 // all the intermediate ThreadGroups to threadGroup2appContext 331 // so we won't spin again. 332 for (ThreadGroup tg = currentThreadGroup; tg != threadGroup; tg = tg.getParent()) { 333 threadGroup2appContext.put(tg, context); 334 } 335 336 // Now we're done, so we cache the latest key/value pair. 337 threadAppContext.set(context); 338 339 return context; 340 } 341 }); 342 } 343 344 return appContext; 345 } 346 347 /** 348 * Returns true if the specified AppContext is the main AppContext. 349 * 350 * @param ctx the context to compare with the main context 351 * @return true if the specified AppContext is the main AppContext. 352 * @since 1.8 353 */ 354 public final static boolean isMainContext(AppContext ctx) { 355 return (ctx != null && ctx == mainAppContext); 356 } 357 358 private final static AppContext getExecutionAppContext() { 359 SecurityManager securityManager = System.getSecurityManager(); 360 if ((securityManager != null) && 361 (securityManager instanceof AWTSecurityManager)) 362 { 363 AWTSecurityManager awtSecMgr = (AWTSecurityManager) securityManager; 364 AppContext secAppContext = awtSecMgr.getAppContext(); 365 return secAppContext; // Return what we're told 366 } 367 return null; 368 } 369 370 private long DISPOSAL_TIMEOUT = 5000; // Default to 5-second timeout 371 // for disposal of all Frames 372 // (we wait for this time twice, 373 // once for dispose(), and once 374 // to clear the EventQueue). 375 376 private long THREAD_INTERRUPT_TIMEOUT = 1000; 377 // Default to 1-second timeout for all 378 // interrupted Threads to exit, and another 379 // 1 second for all stopped Threads to die. 380 381 /** 382 * Disposes of this AppContext, all of its top-level Frames, and 383 * all Threads and ThreadGroups contained within it. 384 * 385 * This method must be called from a Thread which is not contained 386 * within this AppContext. 387 * 388 * @exception IllegalThreadStateException if the current thread is 389 * contained within this AppContext 390 * @since 1.2 391 */ 392 public void dispose() throws IllegalThreadStateException { 393 // Check to be sure that the current Thread isn't in this AppContext 394 if (this.threadGroup.parentOf(Thread.currentThread().getThreadGroup())) { 395 throw new IllegalThreadStateException( 396 "Current Thread is contained within AppContext to be disposed." 397 ); 398 } 399 400 synchronized(this) { 401 if (this.state != State.VALID) { 402 return; // If already disposed or being disposed, bail. 403 } 404 405 this.state = State.BEING_DISPOSED; 406 } 407 408 final PropertyChangeSupport changeSupport = this.changeSupport; 409 if (changeSupport != null) { 410 changeSupport.firePropertyChange(DISPOSED_PROPERTY_NAME, false, true); 411 } 412 413 // First, we post an InvocationEvent to be run on the 414 // EventDispatchThread which disposes of all top-level Frames and TrayIcons 415 416 final Object notificationLock = new Object(); 417 418 Runnable runnable = new Runnable() { 419 public void run() { 420 Window[] windowsToDispose = Window.getOwnerlessWindows(); 421 for (Window w : windowsToDispose) { 422 try { 423 w.dispose(); 424 } catch (Throwable t) { 425 log.finer("exception occured while disposing app context", t); 426 } 427 } 428 AccessController.doPrivileged(new PrivilegedAction() { 429 public Object run() { 430 if (!GraphicsEnvironment.isHeadless() && SystemTray.isSupported()) 431 { 432 SystemTray systemTray = SystemTray.getSystemTray(); 433 TrayIcon[] trayIconsToDispose = systemTray.getTrayIcons(); 434 for (TrayIcon ti : trayIconsToDispose) { 435 systemTray.remove(ti); 436 } 437 } 438 return null; 439 } 440 }); 441 // Alert PropertyChangeListeners that the GUI has been disposed. 442 if (changeSupport != null) { 443 changeSupport.firePropertyChange(GUI_DISPOSED, false, true); 444 } 445 synchronized(notificationLock) { 446 notificationLock.notifyAll(); // Notify caller that we're done 447 } 448 } 449 }; 450 synchronized(notificationLock) { 451 SunToolkit.postEvent(this, 452 new InvocationEvent(Toolkit.getDefaultToolkit(), runnable)); 453 try { 454 notificationLock.wait(DISPOSAL_TIMEOUT); 455 } catch (InterruptedException e) { } 456 } 457 458 // Next, we post another InvocationEvent to the end of the 459 // EventQueue. When it's executed, we know we've executed all 460 // events in the queue. 461 462 runnable = new Runnable() { public void run() { 463 synchronized(notificationLock) { 464 notificationLock.notifyAll(); // Notify caller that we're done 465 } 466 } }; 467 synchronized(notificationLock) { 468 SunToolkit.postEvent(this, 469 new InvocationEvent(Toolkit.getDefaultToolkit(), runnable)); 470 try { 471 notificationLock.wait(DISPOSAL_TIMEOUT); 472 } catch (InterruptedException e) { } 473 } 474 475 // We are done with posting events, so change the state to disposed 476 synchronized(this) { 477 this.state = State.DISPOSED; 478 } 479 480 // Next, we interrupt all Threads in the ThreadGroup 481 this.threadGroup.interrupt(); 482 // Note, the EventDispatchThread we've interrupted may dump an 483 // InterruptedException to the console here. This needs to be 484 // fixed in the EventDispatchThread, not here. 485 486 // Next, we sleep 10ms at a time, waiting for all of the active 487 // Threads in the ThreadGroup to exit. 488 489 long startTime = System.currentTimeMillis(); 490 long endTime = startTime + THREAD_INTERRUPT_TIMEOUT; 491 while ((this.threadGroup.activeCount() > 0) && 492 (System.currentTimeMillis() < endTime)) { 493 try { 494 Thread.sleep(10); 495 } catch (InterruptedException e) { } 496 } 497 498 // Then, we stop any remaining Threads 499 this.threadGroup.stop(); 500 501 // Next, we sleep 10ms at a time, waiting for all of the active 502 // Threads in the ThreadGroup to die. 503 504 startTime = System.currentTimeMillis(); 505 endTime = startTime + THREAD_INTERRUPT_TIMEOUT; 506 while ((this.threadGroup.activeCount() > 0) && 507 (System.currentTimeMillis() < endTime)) { 508 try { 509 Thread.sleep(10); 510 } catch (InterruptedException e) { } 511 } 512 513 // Next, we remove this and all subThreadGroups from threadGroup2appContext 514 int numSubGroups = this.threadGroup.activeGroupCount(); 515 if (numSubGroups > 0) { 516 ThreadGroup [] subGroups = new ThreadGroup[numSubGroups]; 517 numSubGroups = this.threadGroup.enumerate(subGroups); 518 for (int subGroup = 0; subGroup < numSubGroups; subGroup++) { 519 threadGroup2appContext.remove(subGroups[subGroup]); 520 } 521 } 522 threadGroup2appContext.remove(this.threadGroup); 523 524 threadAppContext.set(null); 525 526 // Finally, we destroy the ThreadGroup entirely. 527 try { 528 this.threadGroup.destroy(); 529 } catch (IllegalThreadStateException e) { 530 // Fired if not all the Threads died, ignore it and proceed 531 } 532 533 synchronized (table) { 534 this.table.clear(); // Clear out the Hashtable to ease garbage collection 535 } 536 537 numAppContexts.decrementAndGet(); 538 539 mostRecentKeyValue = null; 540 } 541 542 static final class PostShutdownEventRunnable implements Runnable { 543 private final AppContext appContext; 544 545 public PostShutdownEventRunnable(AppContext ac) { 546 appContext = ac; 547 } 548 549 public void run() { 550 final EventQueue eq = (EventQueue)appContext.get(EVENT_QUEUE_KEY); 551 if (eq != null) { 552 eq.postEvent(AWTAutoShutdown.getShutdownEvent()); 553 } 554 } 555 } 556 557 static final class CreateThreadAction implements PrivilegedAction { 558 private final AppContext appContext; 559 private final Runnable runnable; 560 561 public CreateThreadAction(AppContext ac, Runnable r) { 562 appContext = ac; 563 runnable = r; 564 } 565 566 public Object run() { 567 Thread t = new Thread(appContext.getThreadGroup(), runnable); 568 t.setContextClassLoader(appContext.getContextClassLoader()); 569 t.setPriority(Thread.NORM_PRIORITY + 1); 570 t.setDaemon(true); 571 return t; 572 } 573 } 574 575 static void stopEventDispatchThreads() { 576 for (AppContext appContext: getAppContexts()) { 577 if (appContext.isDisposed()) { 578 continue; 579 } 580 Runnable r = new PostShutdownEventRunnable(appContext); 581 // For security reasons EventQueue.postEvent should only be called 582 // on a thread that belongs to the corresponding thread group. 583 if (appContext != AppContext.getAppContext()) { 584 // Create a thread that belongs to the thread group associated 585 // with the AppContext and invokes EventQueue.postEvent. 586 PrivilegedAction action = new CreateThreadAction(appContext, r); 587 Thread thread = (Thread)AccessController.doPrivileged(action); 588 thread.start(); 589 } else { 590 r.run(); 591 } 592 } 593 } 594 595 private MostRecentKeyValue mostRecentKeyValue = null; 596 private MostRecentKeyValue shadowMostRecentKeyValue = null; 597 598 /** 599 * Returns the value to which the specified key is mapped in this context. 600 * 601 * @param key a key in the AppContext. 602 * @return the value to which the key is mapped in this AppContext; 603 * <code>null</code> if the key is not mapped to any value. 604 * @see #put(Object, Object) 605 * @since 1.2 606 */ 607 public Object get(Object key) { 608 /* 609 * The most recent reference should be updated inside a synchronized 610 * block to avoid a race when put() and get() are executed in 611 * parallel on different threads. 612 */ 613 synchronized (table) { 614 // Note: this most recent key/value caching is thread-hot. 615 // A simple test using SwingSet found that 72% of lookups 616 // were matched using the most recent key/value. By instantiating 617 // a simple MostRecentKeyValue object on cache misses, the 618 // cache hits can be processed without synchronization. 619 620 MostRecentKeyValue recent = mostRecentKeyValue; 621 if ((recent != null) && (recent.key == key)) { 622 return recent.value; 623 } 624 625 Object value = table.get(key); 626 if(mostRecentKeyValue == null) { 627 mostRecentKeyValue = new MostRecentKeyValue(key, value); 628 shadowMostRecentKeyValue = new MostRecentKeyValue(key, value); 629 } else { 630 MostRecentKeyValue auxKeyValue = mostRecentKeyValue; 631 shadowMostRecentKeyValue.setPair(key, value); 632 mostRecentKeyValue = shadowMostRecentKeyValue; 633 shadowMostRecentKeyValue = auxKeyValue; 634 } 635 return value; 636 } 637 } 638 639 /** 640 * Maps the specified <code>key</code> to the specified 641 * <code>value</code> in this AppContext. Neither the key nor the 642 * value can be <code>null</code>. 643 * <p> 644 * The value can be retrieved by calling the <code>get</code> method 645 * with a key that is equal to the original key. 646 * 647 * @param key the AppContext key. 648 * @param value the value. 649 * @return the previous value of the specified key in this 650 * AppContext, or <code>null</code> if it did not have one. 651 * @exception NullPointerException if the key or value is 652 * <code>null</code>. 653 * @see #get(Object) 654 * @since 1.2 655 */ 656 public Object put(Object key, Object value) { 657 synchronized (table) { 658 MostRecentKeyValue recent = mostRecentKeyValue; 659 if ((recent != null) && (recent.key == key)) 660 recent.value = value; 661 return table.put(key, value); 662 } 663 } 664 665 /** 666 * Removes the key (and its corresponding value) from this 667 * AppContext. This method does nothing if the key is not in the 668 * AppContext. 669 * 670 * @param key the key that needs to be removed. 671 * @return the value to which the key had been mapped in this AppContext, 672 * or <code>null</code> if the key did not have a mapping. 673 * @since 1.2 674 */ 675 public Object remove(Object key) { 676 synchronized (table) { 677 MostRecentKeyValue recent = mostRecentKeyValue; 678 if ((recent != null) && (recent.key == key)) 679 recent.value = null; 680 return table.remove(key); 681 } 682 } 683 684 /** 685 * Returns the root ThreadGroup for all Threads contained within 686 * this AppContext. 687 * @since 1.2 688 */ 689 public ThreadGroup getThreadGroup() { 690 return threadGroup; 691 } 692 693 /** 694 * Returns the context ClassLoader that was used to create this 695 * AppContext. 696 * 697 * @see java.lang.Thread#getContextClassLoader 698 */ 699 public ClassLoader getContextClassLoader() { 700 return contextClassLoader; 701 } 702 703 /** 704 * Returns a string representation of this AppContext. 705 * @since 1.2 706 */ 707 @Override 708 public String toString() { 709 return getClass().getName() + "[threadGroup=" + threadGroup.getName() + "]"; 710 } 711 712 /** 713 * Returns an array of all the property change listeners 714 * registered on this component. 715 * 716 * @return all of this component's <code>PropertyChangeListener</code>s 717 * or an empty array if no property change 718 * listeners are currently registered 719 * 720 * @see #addPropertyChangeListener 721 * @see #removePropertyChangeListener 722 * @see #getPropertyChangeListeners(java.lang.String) 723 * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners 724 * @since 1.4 725 */ 726 public synchronized PropertyChangeListener[] getPropertyChangeListeners() { 727 if (changeSupport == null) { 728 return new PropertyChangeListener[0]; 729 } 730 return changeSupport.getPropertyChangeListeners(); 731 } 732 733 /** 734 * Adds a PropertyChangeListener to the listener list for a specific 735 * property. The specified property may be one of the following: 736 * <ul> 737 * <li>if this AppContext is disposed ("disposed")</li> 738 * </ul> 739 * <ul> 740 * <li>if this AppContext's unowned Windows have been disposed 741 * ("guidisposed"). Code to cleanup after the GUI is disposed 742 * (such as LookAndFeel.uninitialize()) should execute in response to 743 * this property being fired. Notifications for the "guidisposed" 744 * property are sent on the event dispatch thread.</li> 745 * </ul> 746 * <p> 747 * If listener is null, no exception is thrown and no action is performed. 748 * 749 * @param propertyName one of the property names listed above 750 * @param listener the PropertyChangeListener to be added 751 * 752 * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 753 * @see #getPropertyChangeListeners(java.lang.String) 754 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 755 */ 756 public synchronized void addPropertyChangeListener( 757 String propertyName, 758 PropertyChangeListener listener) { 759 if (listener == null) { 760 return; 761 } 762 if (changeSupport == null) { 763 changeSupport = new PropertyChangeSupport(this); 764 } 765 changeSupport.addPropertyChangeListener(propertyName, listener); 766 } 767 768 /** 769 * Removes a PropertyChangeListener from the listener list for a specific 770 * property. This method should be used to remove PropertyChangeListeners 771 * that were registered for a specific bound property. 772 * <p> 773 * If listener is null, no exception is thrown and no action is performed. 774 * 775 * @param propertyName a valid property name 776 * @param listener the PropertyChangeListener to be removed 777 * 778 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 779 * @see #getPropertyChangeListeners(java.lang.String) 780 * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) 781 */ 782 public synchronized void removePropertyChangeListener( 783 String propertyName, 784 PropertyChangeListener listener) { 785 if (listener == null || changeSupport == null) { 786 return; 787 } 788 changeSupport.removePropertyChangeListener(propertyName, listener); 789 } 790 791 /** 792 * Returns an array of all the listeners which have been associated 793 * with the named property. 794 * 795 * @return all of the <code>PropertyChangeListeners</code> associated with 796 * the named property or an empty array if no listeners have 797 * been added 798 * 799 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 800 * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 801 * @see #getPropertyChangeListeners 802 * @since 1.4 803 */ 804 public synchronized PropertyChangeListener[] getPropertyChangeListeners( 805 String propertyName) { 806 if (changeSupport == null) { 807 return new PropertyChangeListener[0]; 808 } 809 return changeSupport.getPropertyChangeListeners(propertyName); 810 } 811 812 // Set up JavaAWTAccess in SharedSecrets 813 static { 814 sun.misc.SharedSecrets.setJavaAWTAccess(new sun.misc.JavaAWTAccess() { 815 public Object get(Object key) { 816 AppContext ac = getAppContext(); 817 return (ac == null) ? null : ac.get(key); 818 } 819 public void put(Object key, Object value) { 820 AppContext ac = getAppContext(); 821 if (ac != null) { 822 ac.put(key, value); 823 } 824 } 825 public void remove(Object key) { 826 AppContext ac = getAppContext(); 827 if (ac != null) { 828 ac.remove(key); 829 } 830 } 831 public boolean isDisposed() { 832 AppContext ac = getAppContext(); 833 return (ac == null) ? true : ac.isDisposed(); 834 } 835 public boolean isMainAppContext() { 836 return (numAppContexts.get() == 1 && mainAppContext != null); 837 } 838 public Object getContext() { 839 return getAppContext(); 840 } 841 public Object getExecutionContext() { 842 return getExecutionAppContext(); 843 } 844 public Object get(Object context, Object key) { 845 return ((AppContext)context).get(key); 846 } 847 public void put(Object context, Object key, Object value) { 848 ((AppContext)context).put(key, value); 849 } 850 public void remove(Object context, Object key) { 851 ((AppContext)context).remove(key); 852 } 853 }); 854 } 855 } 856 857 final class MostRecentKeyValue { 858 Object key; 859 Object value; 860 MostRecentKeyValue(Object k, Object v) { 861 key = k; 862 value = v; 863 } 864 void setPair(Object k, Object v) { 865 key = k; 866 value = v; 867 } 868 }