1 /*
   2  * Copyright (c) 2000, 2018, 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 java.util.logging;
  27 
  28 import java.io.*;
  29 import java.util.*;
  30 import java.security.*;
  31 import java.lang.ref.ReferenceQueue;
  32 import java.lang.ref.WeakReference;
  33 import java.util.concurrent.ConcurrentHashMap;
  34 import java.nio.file.Paths;
  35 import java.util.concurrent.CopyOnWriteArrayList;
  36 import java.util.concurrent.locks.ReentrantLock;
  37 import java.util.function.BiFunction;
  38 import java.util.function.Function;
  39 import java.util.function.Predicate;
  40 import java.util.stream.Collectors;
  41 import java.util.stream.Stream;
  42 import jdk.internal.misc.JavaAWTAccess;
  43 import jdk.internal.misc.SharedSecrets;
  44 import sun.util.logging.internal.LoggingProviderImpl;
  45 import static jdk.internal.logger.DefaultLoggerFinder.isSystem;
  46 
  47 /**
  48  * There is a single global LogManager object that is used to
  49  * maintain a set of shared state about Loggers and log services.
  50  * <p>
  51  * This LogManager object:
  52  * <ul>
  53  * <li> Manages a hierarchical namespace of Logger objects.  All
  54  *      named Loggers are stored in this namespace.
  55  * <li> Manages a set of logging control properties.  These are
  56  *      simple key-value pairs that can be used by Handlers and
  57  *      other logging objects to configure themselves.
  58  * </ul>
  59  * <p>
  60  * The global LogManager object can be retrieved using LogManager.getLogManager().
  61  * The LogManager object is created during class initialization and
  62  * cannot subsequently be changed.
  63  * <p>
  64  * At startup the LogManager class is located using the
  65  * java.util.logging.manager system property.
  66  *
  67  * <h3>LogManager Configuration</h3>
  68  *
  69  * A LogManager initializes the logging configuration via
  70  * the {@link #readConfiguration()} method during LogManager initialization.
  71  * By default, LogManager default configuration is used.
  72  * The logging configuration read by LogManager must be in the
  73  * {@linkplain Properties properties file} format.
  74  * <p>
  75  * The LogManager defines two optional system properties that allow control over
  76  * the initial configuration, as specified in the {@link #readConfiguration()}
  77  * method:
  78  * <ul>
  79  * <li>"java.util.logging.config.class"
  80  * <li>"java.util.logging.config.file"
  81  * </ul>
  82  * <p>
  83  * These two system properties may be specified on the command line to the "java"
  84  * command, or as system property definitions passed to JNI_CreateJavaVM.
  85  * <p>
  86  * The {@linkplain Properties properties} for loggers and Handlers will have
  87  * names starting with the dot-separated name for the handler or logger.<br>
  88  * The global logging properties may include:
  89  * <ul>
  90  * <li>A property "handlers".  This defines a whitespace or comma separated
  91  * list of class names for handler classes to load and register as
  92  * handlers on the root Logger (the Logger named "").  Each class
  93  * name must be for a Handler class which has a default constructor.
  94  * Note that these Handlers may be created lazily, when they are
  95  * first used.
  96  *
  97  * <li>A property "&lt;logger&gt;.handlers". This defines a whitespace or
  98  * comma separated list of class names for handlers classes to
  99  * load and register as handlers to the specified logger. Each class
 100  * name must be for a Handler class which has a default constructor.
 101  * Note that these Handlers may be created lazily, when they are
 102  * first used.
 103  *
 104  * <li>A property "&lt;logger&gt;.handlers.ensureCloseOnReset". This defines a
 105  * a boolean value. If "&lt;logger&gt;.handlers" is not defined or is empty,
 106  * this property is ignored. Otherwise it defaults to {@code true}. When the
 107  * value is {@code true}, the handlers associated with the logger are guaranteed
 108  * to be closed on {@linkplain #reset} and shutdown. This can be turned off
 109  * by explicitly setting "&lt;logger&gt;.handlers.ensureCloseOnReset=false" in
 110  * the configuration. Note that turning this property off causes the risk of
 111  * introducing a resource leak, as the logger may get garbage collected before
 112  * {@code reset()} is called, thus preventing its handlers from being closed
 113  * on {@code reset()}. In that case it is the responsibility of the application
 114  * to ensure that the handlers are closed before the logger is garbage
 115  * collected.
 116  *
 117  * <li>A property "&lt;logger&gt;.useParentHandlers". This defines a boolean
 118  * value. By default every logger calls its parent in addition to
 119  * handling the logging message itself, this often result in messages
 120  * being handled by the root logger as well. When setting this property
 121  * to false a Handler needs to be configured for this logger otherwise
 122  * no logging messages are delivered.
 123  *
 124  * <li>A property "config".  This property is intended to allow
 125  * arbitrary configuration code to be run.  The property defines a
 126  * whitespace or comma separated list of class names.  A new instance will be
 127  * created for each named class.  The default constructor of each class
 128  * may execute arbitrary code to update the logging configuration, such as
 129  * setting logger levels, adding handlers, adding filters, etc.
 130  * </ul>
 131  * <p>
 132  * Note that all classes loaded during LogManager configuration are
 133  * first searched on the system class path before any user class path.
 134  * That includes the LogManager class, any config classes, and any
 135  * handler classes.
 136  * <p>
 137  * Loggers are organized into a naming hierarchy based on their
 138  * dot separated names.  Thus "a.b.c" is a child of "a.b", but
 139  * "a.b1" and a.b2" are peers.
 140  * <p>
 141  * All properties whose names end with ".level" are assumed to define
 142  * log levels for Loggers.  Thus "foo.level" defines a log level for
 143  * the logger called "foo" and (recursively) for any of its children
 144  * in the naming hierarchy.  Log Levels are applied in the order they
 145  * are defined in the properties file.  Thus level settings for child
 146  * nodes in the tree should come after settings for their parents.
 147  * The property name ".level" can be used to set the level for the
 148  * root of the tree.
 149  * <p>
 150  * All methods on the LogManager object are multi-thread safe.
 151  *
 152  * @since 1.4
 153 */
 154 
 155 public class LogManager {
 156     // The global LogManager object
 157     private static final LogManager manager;
 158 
 159     // 'props' is assigned within a lock but accessed without it.
 160     // Declaring it volatile makes sure that another thread will not
 161     // be able to see a partially constructed 'props' object.
 162     // (seeing a partially constructed 'props' object can result in
 163     // NPE being thrown in Hashtable.get(), because it leaves the door
 164     // open for props.getProperties() to be called before the construcor
 165     // of Hashtable is actually completed).
 166     private volatile Properties props = new Properties();
 167     private final static Level defaultLevel = Level.INFO;
 168 
 169     // LoggerContext for system loggers and user loggers
 170     private final LoggerContext systemContext = new SystemLoggerContext();
 171     private final LoggerContext userContext = new LoggerContext();
 172     // non final field - make it volatile to make sure that other threads
 173     // will see the new value once ensureLogManagerInitialized() has finished
 174     // executing.
 175     private volatile Logger rootLogger;
 176     // Have we done the primordial reading of the configuration file?
 177     // (Must be done after a suitable amount of java.lang.System
 178     // initialization has been done)
 179     private volatile boolean readPrimordialConfiguration;
 180     // Have we initialized global (root) handlers yet?
 181     // This gets set to STATE_UNINITIALIZED in readConfiguration
 182     private static final int
 183             STATE_INITIALIZED = 0, // initial state
 184             STATE_INITIALIZING = 1,
 185             STATE_READING_CONFIG = 2,
 186             STATE_UNINITIALIZED = 3,
 187             STATE_SHUTDOWN = 4;    // terminal state
 188     private volatile int globalHandlersState; // = STATE_INITIALIZED;
 189     // A concurrency lock for reset(), readConfiguration() and Cleaner.
 190     private final ReentrantLock configurationLock = new ReentrantLock();
 191 
 192     // This list contains the loggers for which some handlers have been
 193     // explicitly configured in the configuration file.
 194     // It prevents these loggers from being arbitrarily garbage collected.
 195     private static final class CloseOnReset {
 196         private final Logger logger;
 197         private CloseOnReset(Logger ref) {
 198             this.logger = Objects.requireNonNull(ref);
 199         }
 200         @Override
 201         public boolean equals(Object other) {
 202             return (other instanceof CloseOnReset) && ((CloseOnReset)other).logger == logger;
 203         }
 204         @Override
 205         public int hashCode() {
 206             return System.identityHashCode(logger);
 207         }
 208         public Logger get() {
 209             return logger;
 210         }
 211         public static CloseOnReset create(Logger logger) {
 212             return new CloseOnReset(logger);
 213         }
 214     }
 215     private final CopyOnWriteArrayList<CloseOnReset> closeOnResetLoggers =
 216             new CopyOnWriteArrayList<>();
 217 
 218 
 219     private final Map<Object, Runnable> listeners =
 220             Collections.synchronizedMap(new IdentityHashMap<>());
 221 
 222     static {
 223         manager = AccessController.doPrivileged(new PrivilegedAction<LogManager>() {
 224             @Override
 225             public LogManager run() {
 226                 LogManager mgr = null;
 227                 String cname = null;
 228                 try {
 229                     cname = System.getProperty("java.util.logging.manager");
 230                     if (cname != null) {
 231                         try {
 232                             @SuppressWarnings("deprecation")
 233                             Object tmp = ClassLoader.getSystemClassLoader()
 234                                 .loadClass(cname).newInstance();
 235                             mgr = (LogManager) tmp;
 236                         } catch (ClassNotFoundException ex) {
 237                             @SuppressWarnings("deprecation")
 238                             Object tmp = Thread.currentThread()
 239                                 .getContextClassLoader().loadClass(cname).newInstance();
 240                             mgr = (LogManager) tmp;
 241                         }
 242                     }
 243                 } catch (Exception ex) {
 244                     System.err.println("Could not load Logmanager \"" + cname + "\"");
 245                     ex.printStackTrace();
 246                 }
 247                 if (mgr == null) {
 248                     mgr = new LogManager();
 249                 }
 250                 return mgr;
 251 
 252             }
 253         });
 254     }
 255 
 256     // This private class is used as a shutdown hook.
 257     // It does a "reset" to close all open handlers.
 258     private class Cleaner extends Thread {
 259 
 260         private Cleaner() {
 261             super(null, null, "Logging-Cleaner", 0, false);
 262             /* Set context class loader to null in order to avoid
 263              * keeping a strong reference to an application classloader.
 264              */
 265             this.setContextClassLoader(null);
 266         }
 267 
 268         @Override
 269         public void run() {
 270             // This is to ensure the LogManager.<clinit> is completed
 271             // before synchronized block. Otherwise deadlocks are possible.
 272             LogManager mgr = manager;
 273 
 274             // set globalHandlersState to STATE_SHUTDOWN atomically so that
 275             // no attempts are made to (re)initialize the handlers or (re)read
 276             // the configuration again. This is terminal state.
 277             configurationLock.lock();
 278             globalHandlersState = STATE_SHUTDOWN;
 279             configurationLock.unlock();
 280 
 281             // Do a reset to close all active handlers.
 282             reset();
 283         }
 284     }
 285 
 286 
 287     /**
 288      * Protected constructor.  This is protected so that container applications
 289      * (such as J2EE containers) can subclass the object.  It is non-public as
 290      * it is intended that there only be one LogManager object, whose value is
 291      * retrieved by calling LogManager.getLogManager.
 292      */
 293     protected LogManager() {
 294         this(checkSubclassPermissions());
 295     }
 296 
 297     private LogManager(Void checked) {
 298 
 299         // Add a shutdown hook to close the global handlers.
 300         try {
 301             Runtime.getRuntime().addShutdownHook(new Cleaner());
 302         } catch (IllegalStateException e) {
 303             // If the VM is already shutting down,
 304             // We do not need to register shutdownHook.
 305         }
 306     }
 307 
 308     private static Void checkSubclassPermissions() {
 309         final SecurityManager sm = System.getSecurityManager();
 310         if (sm != null) {
 311             // These permission will be checked in the LogManager constructor,
 312             // in order to register the Cleaner() thread as a shutdown hook.
 313             // Check them here to avoid the penalty of constructing the object
 314             // etc...
 315             sm.checkPermission(new RuntimePermission("shutdownHooks"));
 316             sm.checkPermission(new RuntimePermission("setContextClassLoader"));
 317         }
 318         return null;
 319     }
 320 
 321     /**
 322      * Lazy initialization: if this instance of manager is the global
 323      * manager then this method will read the initial configuration and
 324      * add the root logger and global logger by calling addLogger().
 325      *
 326      * Note that it is subtly different from what we do in LoggerContext.
 327      * In LoggerContext we're patching up the logger context tree in order to add
 328      * the root and global logger *to the context tree*.
 329      *
 330      * For this to work, addLogger() must have already have been called
 331      * once on the LogManager instance for the default logger being
 332      * added.
 333      *
 334      * This is why ensureLogManagerInitialized() needs to be called before
 335      * any logger is added to any logger context.
 336      *
 337      */
 338     private boolean initializedCalled = false;
 339     private volatile boolean initializationDone = false;
 340     final void ensureLogManagerInitialized() {
 341         final LogManager owner = this;
 342         if (initializationDone || owner != manager) {
 343             // we don't want to do this twice, and we don't want to do
 344             // this on private manager instances.
 345             return;
 346         }
 347 
 348         // Maybe another thread has called ensureLogManagerInitialized()
 349         // before us and is still executing it. If so we will block until
 350         // the log manager has finished initialized, then acquire the monitor,
 351         // notice that initializationDone is now true and return.
 352         // Otherwise - we have come here first! We will acquire the monitor,
 353         // see that initializationDone is still false, and perform the
 354         // initialization.
 355         //
 356         configurationLock.lock();
 357         try {
 358             // If initializedCalled is true it means that we're already in
 359             // the process of initializing the LogManager in this thread.
 360             // There has been a recursive call to ensureLogManagerInitialized().
 361             final boolean isRecursiveInitialization = (initializedCalled == true);
 362 
 363             assert initializedCalled || !initializationDone
 364                     : "Initialization can't be done if initialized has not been called!";
 365 
 366             if (isRecursiveInitialization || initializationDone) {
 367                 // If isRecursiveInitialization is true it means that we're
 368                 // already in the process of initializing the LogManager in
 369                 // this thread. There has been a recursive call to
 370                 // ensureLogManagerInitialized(). We should not proceed as
 371                 // it would lead to infinite recursion.
 372                 //
 373                 // If initializationDone is true then it means the manager
 374                 // has finished initializing; just return: we're done.
 375                 return;
 376             }
 377             // Calling addLogger below will in turn call requiresDefaultLogger()
 378             // which will call ensureLogManagerInitialized().
 379             // We use initializedCalled to break the recursion.
 380             initializedCalled = true;
 381             try {
 382                 AccessController.doPrivileged(new PrivilegedAction<Object>() {
 383                     @Override
 384                     public Object run() {
 385                         assert rootLogger == null;
 386                         assert initializedCalled && !initializationDone;
 387 
 388                         // create root logger before reading primordial
 389                         // configuration - to ensure that it will be added
 390                         // before the global logger, and not after.
 391                         final Logger root = owner.rootLogger = owner.new RootLogger();
 392 
 393                         // Read configuration.
 394                         owner.readPrimordialConfiguration();
 395 
 396                         // Create and retain Logger for the root of the namespace.
 397                         owner.addLogger(root);
 398 
 399                         // Initialize level if not yet initialized
 400                         if (!root.isLevelInitialized()) {
 401                             root.setLevel(defaultLevel);
 402                         }
 403 
 404                         // Adding the global Logger.
 405                         // Do not call Logger.getGlobal() here as this might trigger
 406                         // subtle inter-dependency issues.
 407                         @SuppressWarnings("deprecation")
 408                         final Logger global = Logger.global;
 409 
 410                         // Make sure the global logger will be registered in the
 411                         // global manager
 412                         owner.addLogger(global);
 413                         return null;
 414                     }
 415                 });
 416             } finally {
 417                 initializationDone = true;
 418             }
 419         } finally {
 420             configurationLock.unlock();
 421         }
 422     }
 423 
 424     /**
 425      * Returns the global LogManager object.
 426      * @return the global LogManager object
 427      */
 428     public static LogManager getLogManager() {
 429         if (manager != null) {
 430             manager.ensureLogManagerInitialized();
 431         }
 432         return manager;
 433     }
 434 
 435     private void readPrimordialConfiguration() { // must be called while holding configurationLock
 436         if (!readPrimordialConfiguration) {
 437             // If System.in/out/err are null, it's a good
 438             // indication that we're still in the
 439             // bootstrapping phase
 440             if (System.out == null) {
 441                 return;
 442             }
 443             readPrimordialConfiguration = true;
 444             try {
 445                 readConfiguration();
 446 
 447                 // Platform loggers begin to delegate to java.util.logging.Logger
 448                 jdk.internal.logger.BootstrapLogger.redirectTemporaryLoggers();
 449 
 450             } catch (Exception ex) {
 451                 assert false : "Exception raised while reading logging configuration: " + ex;
 452             }
 453         }
 454     }
 455 
 456     // LoggerContext maps from AppContext
 457     private WeakHashMap<Object, LoggerContext> contextsMap = null;
 458 
 459     // Returns the LoggerContext for the user code (i.e. application or AppContext).
 460     // Loggers are isolated from each AppContext.
 461     private LoggerContext getUserContext() {
 462         LoggerContext context = null;
 463 
 464         SecurityManager sm = System.getSecurityManager();
 465         JavaAWTAccess javaAwtAccess = SharedSecrets.getJavaAWTAccess();
 466         if (sm != null && javaAwtAccess != null) {
 467             // for each applet, it has its own LoggerContext isolated from others
 468             final Object ecx = javaAwtAccess.getAppletContext();
 469             if (ecx != null) {
 470                 synchronized (javaAwtAccess) {
 471                     // find the AppContext of the applet code
 472                     // will be null if we are in the main app context.
 473                     if (contextsMap == null) {
 474                         contextsMap = new WeakHashMap<>();
 475                     }
 476                     context = contextsMap.get(ecx);
 477                     if (context == null) {
 478                         // Create a new LoggerContext for the applet.
 479                         context = new LoggerContext();
 480                         contextsMap.put(ecx, context);
 481                     }
 482                 }
 483             }
 484         }
 485         // for standalone app, return userContext
 486         return context != null ? context : userContext;
 487     }
 488 
 489     // The system context.
 490     final LoggerContext getSystemContext() {
 491         return systemContext;
 492     }
 493 
 494     private List<LoggerContext> contexts() {
 495         List<LoggerContext> cxs = new ArrayList<>();
 496         cxs.add(getSystemContext());
 497         cxs.add(getUserContext());
 498         return cxs;
 499     }
 500 
 501     // Find or create a specified logger instance. If a logger has
 502     // already been created with the given name it is returned.
 503     // Otherwise a new logger instance is created and registered
 504     // in the LogManager global namespace.
 505     // This method will always return a non-null Logger object.
 506     // Synchronization is not required here. All synchronization for
 507     // adding a new Logger object is handled by addLogger().
 508     //
 509     // This method must delegate to the LogManager implementation to
 510     // add a new Logger or return the one that has been added previously
 511     // as a LogManager subclass may override the addLogger, getLogger,
 512     // readConfiguration, and other methods.
 513     Logger demandLogger(String name, String resourceBundleName, Class<?> caller) {
 514         final Module module = caller == null ? null : caller.getModule();
 515         return demandLogger(name, resourceBundleName, module);
 516     }
 517 
 518     Logger demandLogger(String name, String resourceBundleName, Module module) {
 519         Logger result = getLogger(name);
 520         if (result == null) {
 521             // only allocate the new logger once
 522             Logger newLogger = new Logger(name, resourceBundleName,
 523                                           module, this, false);
 524             do {
 525                 if (addLogger(newLogger)) {
 526                     // We successfully added the new Logger that we
 527                     // created above so return it without refetching.
 528                     return newLogger;
 529                 }
 530 
 531                 // We didn't add the new Logger that we created above
 532                 // because another thread added a Logger with the same
 533                 // name after our null check above and before our call
 534                 // to addLogger(). We have to refetch the Logger because
 535                 // addLogger() returns a boolean instead of the Logger
 536                 // reference itself. However, if the thread that created
 537                 // the other Logger is not holding a strong reference to
 538                 // the other Logger, then it is possible for the other
 539                 // Logger to be GC'ed after we saw it in addLogger() and
 540                 // before we can refetch it. If it has been GC'ed then
 541                 // we'll just loop around and try again.
 542                 result = getLogger(name);
 543             } while (result == null);
 544         }
 545         return result;
 546     }
 547 
 548     Logger demandSystemLogger(String name, String resourceBundleName, Class<?> caller) {
 549         final Module module = caller == null ? null : caller.getModule();
 550         return demandSystemLogger(name, resourceBundleName, module);
 551     }
 552 
 553     Logger demandSystemLogger(String name, String resourceBundleName, Module module) {
 554         // Add a system logger in the system context's namespace
 555         final Logger sysLogger = getSystemContext()
 556                 .demandLogger(name, resourceBundleName, module);
 557 
 558         // Add the system logger to the LogManager's namespace if not exist
 559         // so that there is only one single logger of the given name.
 560         // System loggers are visible to applications unless a logger of
 561         // the same name has been added.
 562         Logger logger;
 563         do {
 564             // First attempt to call addLogger instead of getLogger
 565             // This would avoid potential bug in custom LogManager.getLogger
 566             // implementation that adds a logger if does not exist
 567             if (addLogger(sysLogger)) {
 568                 // successfully added the new system logger
 569                 logger = sysLogger;
 570             } else {
 571                 logger = getLogger(name);
 572             }
 573         } while (logger == null);
 574 
 575         // LogManager will set the sysLogger's handlers via LogManager.addLogger method.
 576         if (logger != sysLogger) {
 577             // if logger already exists we merge the two logger configurations.
 578             final Logger l = logger;
 579             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 580                 @Override
 581                 public Void run() {
 582                     l.mergeWithSystemLogger(sysLogger);
 583                     return null;
 584                 }
 585             });
 586         }
 587         return sysLogger;
 588     }
 589 
 590     // LoggerContext maintains the logger namespace per context.
 591     // The default LogManager implementation has one system context and user
 592     // context.  The system context is used to maintain the namespace for
 593     // all system loggers and is queried by the system code.  If a system logger
 594     // doesn't exist in the user context, it'll also be added to the user context.
 595     // The user context is queried by the user code and all other loggers are
 596     // added in the user context.
 597     class LoggerContext {
 598         // Table of named Loggers that maps names to Loggers.
 599         private final ConcurrentHashMap<String,LoggerWeakRef> namedLoggers =
 600                 new ConcurrentHashMap<>();
 601         // Tree of named Loggers
 602         private final LogNode root;
 603         private LoggerContext() {
 604             this.root = new LogNode(null, this);
 605         }
 606 
 607 
 608         // Tells whether default loggers are required in this context.
 609         // If true, the default loggers will be lazily added.
 610         final boolean requiresDefaultLoggers() {
 611             final boolean requiresDefaultLoggers = (getOwner() == manager);
 612             if (requiresDefaultLoggers) {
 613                 getOwner().ensureLogManagerInitialized();
 614             }
 615             return requiresDefaultLoggers;
 616         }
 617 
 618         // This context's LogManager.
 619         final LogManager getOwner() {
 620             return LogManager.this;
 621         }
 622 
 623         // This context owner's root logger, which if not null, and if
 624         // the context requires default loggers, will be added to the context
 625         // logger's tree.
 626         final Logger getRootLogger() {
 627             return getOwner().rootLogger;
 628         }
 629 
 630         // The global logger, which if not null, and if
 631         // the context requires default loggers, will be added to the context
 632         // logger's tree.
 633         final Logger getGlobalLogger() {
 634             @SuppressWarnings("deprecation") // avoids initialization cycles.
 635             final Logger global = Logger.global;
 636             return global;
 637         }
 638 
 639         Logger demandLogger(String name, String resourceBundleName, Module module) {
 640             // a LogManager subclass may have its own implementation to add and
 641             // get a Logger.  So delegate to the LogManager to do the work.
 642             final LogManager owner = getOwner();
 643             return owner.demandLogger(name, resourceBundleName, module);
 644         }
 645 
 646 
 647         // Due to subtle deadlock issues getUserContext() no longer
 648         // calls addLocalLogger(rootLogger);
 649         // Therefore - we need to add the default loggers later on.
 650         // Checks that the context is properly initialized
 651         // This is necessary before calling e.g. find(name)
 652         // or getLoggerNames()
 653         //
 654         private void ensureInitialized() {
 655             if (requiresDefaultLoggers()) {
 656                 // Ensure that the root and global loggers are set.
 657                 ensureDefaultLogger(getRootLogger());
 658                 ensureDefaultLogger(getGlobalLogger());
 659             }
 660         }
 661 
 662 
 663         Logger findLogger(String name) {
 664             // Attempt to find logger without locking.
 665             LoggerWeakRef ref = namedLoggers.get(name);
 666             Logger logger = ref == null ? null : ref.get();
 667 
 668             // if logger is not null, then we can return it right away.
 669             // if name is "" or "global" and logger is null
 670             // we need to fall through and check that this context is
 671             // initialized.
 672             // if ref is not null and logger is null we also need to
 673             // fall through.
 674             if (logger != null || (ref == null && !name.isEmpty()
 675                     && !name.equals(Logger.GLOBAL_LOGGER_NAME))) {
 676                 return logger;
 677             }
 678 
 679             // We either found a stale reference, or we were looking for
 680             // "" or "global" and didn't find them.
 681             // Make sure context is initialized (has the default loggers),
 682             // and look up again, cleaning the stale reference if it hasn't
 683             // been cleaned up in between. All this needs to be done inside
 684             // a synchronized block.
 685             synchronized(this) {
 686                 // ensure that this context is properly initialized before
 687                 // looking for loggers.
 688                 ensureInitialized();
 689                 ref = namedLoggers.get(name);
 690                 if (ref == null) {
 691                     return null;
 692                 }
 693                 logger = ref.get();
 694                 if (logger == null) {
 695                     // The namedLoggers map holds stale weak reference
 696                     // to a logger which has been GC-ed.
 697                     ref.dispose();
 698                 }
 699                 return logger;
 700             }
 701         }
 702 
 703         // This method is called before adding a logger to the
 704         // context.
 705         // 'logger' is the context that will be added.
 706         // This method will ensure that the defaults loggers are added
 707         // before adding 'logger'.
 708         //
 709         private void ensureAllDefaultLoggers(Logger logger) {
 710             if (requiresDefaultLoggers()) {
 711                 final String name = logger.getName();
 712                 if (!name.isEmpty()) {
 713                     ensureDefaultLogger(getRootLogger());
 714                     if (!Logger.GLOBAL_LOGGER_NAME.equals(name)) {
 715                         ensureDefaultLogger(getGlobalLogger());
 716                     }
 717                 }
 718             }
 719         }
 720 
 721         private void ensureDefaultLogger(Logger logger) {
 722             // Used for lazy addition of root logger and global logger
 723             // to a LoggerContext.
 724 
 725             // This check is simple sanity: we do not want that this
 726             // method be called for anything else than Logger.global
 727             // or owner.rootLogger.
 728             if (!requiresDefaultLoggers() || logger == null
 729                     || logger != getGlobalLogger() && logger != LogManager.this.rootLogger ) {
 730 
 731                 // the case where we have a non null logger which is neither
 732                 // Logger.global nor manager.rootLogger indicates a serious
 733                 // issue - as ensureDefaultLogger should never be called
 734                 // with any other loggers than one of these two (or null - if
 735                 // e.g manager.rootLogger is not yet initialized)...
 736                 assert logger == null;
 737 
 738                 return;
 739             }
 740 
 741             // Adds the logger if it's not already there.
 742             if (!namedLoggers.containsKey(logger.getName())) {
 743                 // It is important to prevent addLocalLogger to
 744                 // call ensureAllDefaultLoggers when we're in the process
 745                 // off adding one of those default loggers - as this would
 746                 // immediately cause a stack overflow.
 747                 // Therefore we must pass addDefaultLoggersIfNeeded=false,
 748                 // even if requiresDefaultLoggers is true.
 749                 addLocalLogger(logger, false);
 750             }
 751         }
 752 
 753         boolean addLocalLogger(Logger logger) {
 754             // no need to add default loggers if it's not required
 755             return addLocalLogger(logger, requiresDefaultLoggers());
 756         }
 757 
 758         // Add a logger to this context.  This method will only set its level
 759         // and process parent loggers.  It doesn't set its handlers.
 760         synchronized boolean addLocalLogger(Logger logger, boolean addDefaultLoggersIfNeeded) {
 761             // addDefaultLoggersIfNeeded serves to break recursion when adding
 762             // default loggers. If we're adding one of the default loggers
 763             // (we're being called from ensureDefaultLogger()) then
 764             // addDefaultLoggersIfNeeded will be false: we don't want to
 765             // call ensureAllDefaultLoggers again.
 766             //
 767             // Note: addDefaultLoggersIfNeeded can also be false when
 768             //       requiresDefaultLoggers is false - since calling
 769             //       ensureAllDefaultLoggers would have no effect in this case.
 770             if (addDefaultLoggersIfNeeded) {
 771                 ensureAllDefaultLoggers(logger);
 772             }
 773 
 774             final String name = logger.getName();
 775             if (name == null) {
 776                 throw new NullPointerException();
 777             }
 778             LoggerWeakRef ref = namedLoggers.get(name);
 779             if (ref != null) {
 780                 if (ref.get() == null) {
 781                     // It's possible that the Logger was GC'ed after a
 782                     // drainLoggerRefQueueBounded() call above so allow
 783                     // a new one to be registered.
 784                     ref.dispose();
 785                 } else {
 786                     // We already have a registered logger with the given name.
 787                     return false;
 788                 }
 789             }
 790 
 791             // We're adding a new logger.
 792             // Note that we are creating a weak reference here.
 793             final LogManager owner = getOwner();
 794             logger.setLogManager(owner);
 795             ref = owner.new LoggerWeakRef(logger);
 796 
 797             // Apply any initial level defined for the new logger, unless
 798             // the logger's level is already initialized
 799             Level level = owner.getLevelProperty(name + ".level", null);
 800             if (level != null && !logger.isLevelInitialized()) {
 801                 doSetLevel(logger, level);
 802             }
 803 
 804             // instantiation of the handler is done in the LogManager.addLogger
 805             // implementation as a handler class may be only visible to LogManager
 806             // subclass for the custom log manager case
 807             processParentHandlers(logger, name, VisitedLoggers.NEVER);
 808 
 809             // Find the new node and its parent.
 810             LogNode node = getNode(name);
 811             node.loggerRef = ref;
 812             Logger parent = null;
 813             LogNode nodep = node.parent;
 814             while (nodep != null) {
 815                 LoggerWeakRef nodeRef = nodep.loggerRef;
 816                 if (nodeRef != null) {
 817                     parent = nodeRef.get();
 818                     if (parent != null) {
 819                         break;
 820                     }
 821                 }
 822                 nodep = nodep.parent;
 823             }
 824 
 825             if (parent != null) {
 826                 doSetParent(logger, parent);
 827             }
 828             // Walk over the children and tell them we are their new parent.
 829             node.walkAndSetParent(logger);
 830             // new LogNode is ready so tell the LoggerWeakRef about it
 831             ref.setNode(node);
 832 
 833             // Do not publish 'ref' in namedLoggers before the logger tree
 834             // is fully updated - because the named logger will be visible as
 835             // soon as it is published in namedLoggers (findLogger takes
 836             // benefit of the ConcurrentHashMap implementation of namedLoggers
 837             // to avoid synchronizing on retrieval when that is possible).
 838             namedLoggers.put(name, ref);
 839             return true;
 840         }
 841 
 842         void removeLoggerRef(String name, LoggerWeakRef ref) {
 843             namedLoggers.remove(name, ref);
 844         }
 845 
 846         synchronized Enumeration<String> getLoggerNames() {
 847             // ensure that this context is properly initialized before
 848             // returning logger names.
 849             ensureInitialized();
 850             return Collections.enumeration(namedLoggers.keySet());
 851         }
 852 
 853         // If logger.getUseParentHandlers() returns 'true' and any of the logger's
 854         // parents have levels or handlers defined, make sure they are instantiated.
 855         private void processParentHandlers(final Logger logger, final String name,
 856                Predicate<Logger> visited) {
 857             final LogManager owner = getOwner();
 858             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 859                 @Override
 860                 public Void run() {
 861                     if (logger != owner.rootLogger) {
 862                         boolean useParent = owner.getBooleanProperty(name + ".useParentHandlers", true);
 863                         if (!useParent) {
 864                             logger.setUseParentHandlers(false);
 865                         }
 866                     }
 867                     return null;
 868                 }
 869             });
 870 
 871             int ix = 1;
 872             for (;;) {
 873                 int ix2 = name.indexOf('.', ix);
 874                 if (ix2 < 0) {
 875                     break;
 876                 }
 877                 String pname = name.substring(0, ix2);
 878                 if (owner.getProperty(pname + ".level") != null ||
 879                     owner.getProperty(pname + ".handlers") != null) {
 880                     // This pname has a level/handlers definition.
 881                     // Make sure it exists.
 882                     if (visited.test(demandLogger(pname, null, null))) {
 883                         break;
 884                     }
 885                 }
 886                 ix = ix2+1;
 887             }
 888         }
 889 
 890         // Gets a node in our tree of logger nodes.
 891         // If necessary, create it.
 892         LogNode getNode(String name) {
 893             if (name == null || name.equals("")) {
 894                 return root;
 895             }
 896             LogNode node = root;
 897             while (name.length() > 0) {
 898                 int ix = name.indexOf('.');
 899                 String head;
 900                 if (ix > 0) {
 901                     head = name.substring(0, ix);
 902                     name = name.substring(ix + 1);
 903                 } else {
 904                     head = name;
 905                     name = "";
 906                 }
 907                 if (node.children == null) {
 908                     node.children = new HashMap<>();
 909                 }
 910                 LogNode child = node.children.get(head);
 911                 if (child == null) {
 912                     child = new LogNode(node, this);
 913                     node.children.put(head, child);
 914                 }
 915                 node = child;
 916             }
 917             return node;
 918         }
 919     }
 920 
 921     final class SystemLoggerContext extends LoggerContext {
 922         // Add a system logger in the system context's namespace as well as
 923         // in the LogManager's namespace if not exist so that there is only
 924         // one single logger of the given name.  System loggers are visible
 925         // to applications unless a logger of the same name has been added.
 926         @Override
 927         Logger demandLogger(String name, String resourceBundleName,
 928                             Module module) {
 929             Logger result = findLogger(name);
 930             if (result == null) {
 931                 // only allocate the new system logger once
 932                 Logger newLogger = new Logger(name, resourceBundleName,
 933                                               module, getOwner(), true);
 934                 do {
 935                     if (addLocalLogger(newLogger)) {
 936                         // We successfully added the new Logger that we
 937                         // created above so return it without refetching.
 938                         result = newLogger;
 939                     } else {
 940                         // We didn't add the new Logger that we created above
 941                         // because another thread added a Logger with the same
 942                         // name after our null check above and before our call
 943                         // to addLogger(). We have to refetch the Logger because
 944                         // addLogger() returns a boolean instead of the Logger
 945                         // reference itself. However, if the thread that created
 946                         // the other Logger is not holding a strong reference to
 947                         // the other Logger, then it is possible for the other
 948                         // Logger to be GC'ed after we saw it in addLogger() and
 949                         // before we can refetch it. If it has been GC'ed then
 950                         // we'll just loop around and try again.
 951                         result = findLogger(name);
 952                     }
 953                 } while (result == null);
 954             }
 955             return result;
 956         }
 957     }
 958 
 959     // Add new per logger handlers.
 960     // We need to raise privilege here. All our decisions will
 961     // be made based on the logging configuration, which can
 962     // only be modified by trusted code.
 963     private void loadLoggerHandlers(final Logger logger, final String name,
 964                                     final String handlersPropertyName)
 965     {
 966         AccessController.doPrivileged(new PrivilegedAction<Void>() {
 967             @Override
 968             public Void run() {
 969                 setLoggerHandlers(logger, name, handlersPropertyName,
 970                     createLoggerHandlers(name, handlersPropertyName));
 971                 return null;
 972             }
 973         });
 974     }
 975 
 976     private void setLoggerHandlers(final Logger logger, final String name,
 977                                    final String handlersPropertyName,
 978                                    List<Handler> handlers)
 979     {
 980         final boolean ensureCloseOnReset = ! handlers.isEmpty()
 981                     && getBooleanProperty(handlersPropertyName + ".ensureCloseOnReset",true);
 982         int count = 0;
 983         for (Handler hdl : handlers) {
 984             logger.addHandler(hdl);
 985             if (++count == 1 && ensureCloseOnReset) {
 986                 // add this logger to the closeOnResetLoggers list.
 987                 closeOnResetLoggers.addIfAbsent(CloseOnReset.create(logger));
 988             }
 989         }
 990     }
 991 
 992     private List<Handler> createLoggerHandlers(final String name,
 993                                                final String handlersPropertyName)
 994     {
 995         String names[] = parseClassNames(handlersPropertyName);
 996         List<Handler> handlers = new ArrayList<>(names.length);
 997         for (String type : names) {
 998             try {
 999                 @SuppressWarnings("deprecation")
1000                 Object o = ClassLoader.getSystemClassLoader().loadClass(type).newInstance();
1001                 Handler hdl = (Handler) o;
1002                 // Check if there is a property defining the
1003                 // this handler's level.
1004                 String levs = getProperty(type + ".level");
1005                 if (levs != null) {
1006                     Level l = Level.findLevel(levs);
1007                     if (l != null) {
1008                         hdl.setLevel(l);
1009                     } else {
1010                         // Probably a bad level. Drop through.
1011                         System.err.println("Can't set level for " + type);
1012                     }
1013                 }
1014                 // Add this Handler to the logger
1015                 handlers.add(hdl);
1016             } catch (Exception ex) {
1017                 System.err.println("Can't load log handler \"" + type + "\"");
1018                 System.err.println("" + ex);
1019                 ex.printStackTrace();
1020             }
1021         }
1022 
1023         return handlers;
1024     }
1025 
1026 
1027     // loggerRefQueue holds LoggerWeakRef objects for Logger objects
1028     // that have been GC'ed.
1029     private final ReferenceQueue<Logger> loggerRefQueue
1030         = new ReferenceQueue<>();
1031 
1032     // Package-level inner class.
1033     // Helper class for managing WeakReferences to Logger objects.
1034     //
1035     // LogManager.namedLoggers
1036     //     - has weak references to all named Loggers
1037     //     - namedLoggers keeps the LoggerWeakRef objects for the named
1038     //       Loggers around until we can deal with the book keeping for
1039     //       the named Logger that is being GC'ed.
1040     // LogManager.LogNode.loggerRef
1041     //     - has a weak reference to a named Logger
1042     //     - the LogNode will also keep the LoggerWeakRef objects for
1043     //       the named Loggers around; currently LogNodes never go away.
1044     // Logger.kids
1045     //     - has a weak reference to each direct child Logger; this
1046     //       includes anonymous and named Loggers
1047     //     - anonymous Loggers are always children of the rootLogger
1048     //       which is a strong reference; rootLogger.kids keeps the
1049     //       LoggerWeakRef objects for the anonymous Loggers around
1050     //       until we can deal with the book keeping.
1051     //
1052     final class LoggerWeakRef extends WeakReference<Logger> {
1053         private String                name;       // for namedLoggers cleanup
1054         private LogNode               node;       // for loggerRef cleanup
1055         private WeakReference<Logger> parentRef;  // for kids cleanup
1056         private boolean disposed = false;         // avoid calling dispose twice
1057 
1058         LoggerWeakRef(Logger logger) {
1059             super(logger, loggerRefQueue);
1060 
1061             name = logger.getName();  // save for namedLoggers cleanup
1062         }
1063 
1064         // dispose of this LoggerWeakRef object
1065         void dispose() {
1066             // Avoid calling dispose twice. When a Logger is gc'ed, its
1067             // LoggerWeakRef will be enqueued.
1068             // However, a new logger of the same name may be added (or looked
1069             // up) before the queue is drained. When that happens, dispose()
1070             // will be called by addLocalLogger() or findLogger().
1071             // Later when the queue is drained, dispose() will be called again
1072             // for the same LoggerWeakRef. Marking LoggerWeakRef as disposed
1073             // avoids processing the data twice (even though the code should
1074             // now be reentrant).
1075             synchronized(this) {
1076                 // Note to maintainers:
1077                 // Be careful not to call any method that tries to acquire
1078                 // another lock from within this block - as this would surely
1079                 // lead to deadlocks, given that dispose() can be called by
1080                 // multiple threads, and from within different synchronized
1081                 // methods/blocks.
1082                 if (disposed) return;
1083                 disposed = true;
1084             }
1085 
1086             final LogNode n = node;
1087             if (n != null) {
1088                 // n.loggerRef can only be safely modified from within
1089                 // a lock on LoggerContext. removeLoggerRef is already
1090                 // synchronized on LoggerContext so calling
1091                 // n.context.removeLoggerRef from within this lock is safe.
1092                 synchronized (n.context) {
1093                     // if we have a LogNode, then we were a named Logger
1094                     // so clear namedLoggers weak ref to us
1095                     n.context.removeLoggerRef(name, this);
1096                     name = null;  // clear our ref to the Logger's name
1097 
1098                     // LogNode may have been reused - so only clear
1099                     // LogNode.loggerRef if LogNode.loggerRef == this
1100                     if (n.loggerRef == this) {
1101                         n.loggerRef = null;  // clear LogNode's weak ref to us
1102                     }
1103                     node = null;            // clear our ref to LogNode
1104                 }
1105             }
1106 
1107             if (parentRef != null) {
1108                 // this LoggerWeakRef has or had a parent Logger
1109                 Logger parent = parentRef.get();
1110                 if (parent != null) {
1111                     // the parent Logger is still there so clear the
1112                     // parent Logger's weak ref to us
1113                     parent.removeChildLogger(this);
1114                 }
1115                 parentRef = null;  // clear our weak ref to the parent Logger
1116             }
1117         }
1118 
1119         // set the node field to the specified value
1120         void setNode(LogNode node) {
1121             this.node = node;
1122         }
1123 
1124         // set the parentRef field to the specified value
1125         void setParentRef(WeakReference<Logger> parentRef) {
1126             this.parentRef = parentRef;
1127         }
1128     }
1129 
1130     // Package-level method.
1131     // Drain some Logger objects that have been GC'ed.
1132     //
1133     // drainLoggerRefQueueBounded() is called by addLogger() below
1134     // and by Logger.getAnonymousLogger(String) so we'll drain up to
1135     // MAX_ITERATIONS GC'ed Loggers for every Logger we add.
1136     //
1137     // On a WinXP VMware client, a MAX_ITERATIONS value of 400 gives
1138     // us about a 50/50 mix in increased weak ref counts versus
1139     // decreased weak ref counts in the AnonLoggerWeakRefLeak test.
1140     // Here are stats for cleaning up sets of 400 anonymous Loggers:
1141     //   - test duration 1 minute
1142     //   - sample size of 125 sets of 400
1143     //   - average: 1.99 ms
1144     //   - minimum: 0.57 ms
1145     //   - maximum: 25.3 ms
1146     //
1147     // The same config gives us a better decreased weak ref count
1148     // than increased weak ref count in the LoggerWeakRefLeak test.
1149     // Here are stats for cleaning up sets of 400 named Loggers:
1150     //   - test duration 2 minutes
1151     //   - sample size of 506 sets of 400
1152     //   - average: 0.57 ms
1153     //   - minimum: 0.02 ms
1154     //   - maximum: 10.9 ms
1155     //
1156     private final static int MAX_ITERATIONS = 400;
1157     final void drainLoggerRefQueueBounded() {
1158         for (int i = 0; i < MAX_ITERATIONS; i++) {
1159             if (loggerRefQueue == null) {
1160                 // haven't finished loading LogManager yet
1161                 break;
1162             }
1163 
1164             LoggerWeakRef ref = (LoggerWeakRef) loggerRefQueue.poll();
1165             if (ref == null) {
1166                 break;
1167             }
1168             // a Logger object has been GC'ed so clean it up
1169             ref.dispose();
1170         }
1171     }
1172 
1173     /**
1174      * Add a named logger.  This does nothing and returns false if a logger
1175      * with the same name is already registered.
1176      * <p>
1177      * The Logger factory methods call this method to register each
1178      * newly created Logger.
1179      * <p>
1180      * The application should retain its own reference to the Logger
1181      * object to avoid it being garbage collected.  The LogManager
1182      * may only retain a weak reference.
1183      *
1184      * @param   logger the new logger.
1185      * @return  true if the argument logger was registered successfully,
1186      *          false if a logger of that name already exists.
1187      * @exception NullPointerException if the logger name is null.
1188      */
1189     public boolean addLogger(Logger logger) {
1190         final String name = logger.getName();
1191         if (name == null) {
1192             throw new NullPointerException();
1193         }
1194         drainLoggerRefQueueBounded();
1195         LoggerContext cx = getUserContext();
1196         if (cx.addLocalLogger(logger) || forceLoadHandlers(logger)) {
1197             // Do we have a per logger handler too?
1198             // Note: this will add a 200ms penalty
1199             loadLoggerHandlers(logger, name, name + ".handlers");
1200             return true;
1201         } else {
1202             return false;
1203         }
1204     }
1205 
1206 
1207     // Checks whether the given logger is a special logger
1208     // that still requires handler initialization.
1209     // This method will only return true for the root and
1210     // global loggers and only if called by the thread that
1211     // performs initialization of the LogManager, during that
1212     // initialization. Must only be called by addLogger.
1213     @SuppressWarnings("deprecation")
1214     private boolean forceLoadHandlers(Logger logger) {
1215         // Called just after reading the primordial configuration, in
1216         // the same thread that reads it.
1217         // The root and global logger would already be present in the context
1218         // by this point, but we would not have called loadLoggerHandlers
1219         // yet.
1220         assert logger != null;
1221         return (logger == rootLogger ||  logger == Logger.global)
1222                 && !initializationDone
1223                 && initializedCalled
1224                 && configurationLock.isHeldByCurrentThread();
1225     }
1226 
1227     // Private method to set a level on a logger.
1228     // If necessary, we raise privilege before doing the call.
1229     private static void doSetLevel(final Logger logger, final Level level) {
1230         SecurityManager sm = System.getSecurityManager();
1231         if (sm == null) {
1232             // There is no security manager, so things are easy.
1233             logger.setLevel(level);
1234             return;
1235         }
1236         // There is a security manager.  Raise privilege before
1237         // calling setLevel.
1238         AccessController.doPrivileged(new PrivilegedAction<Object>() {
1239             @Override
1240             public Object run() {
1241                 logger.setLevel(level);
1242                 return null;
1243             }});
1244     }
1245 
1246     // Private method to set a parent on a logger.
1247     // If necessary, we raise privilege before doing the setParent call.
1248     private static void doSetParent(final Logger logger, final Logger parent) {
1249         SecurityManager sm = System.getSecurityManager();
1250         if (sm == null) {
1251             // There is no security manager, so things are easy.
1252             logger.setParent(parent);
1253             return;
1254         }
1255         // There is a security manager.  Raise privilege before
1256         // calling setParent.
1257         AccessController.doPrivileged(new PrivilegedAction<Object>() {
1258             @Override
1259             public Object run() {
1260                 logger.setParent(parent);
1261                 return null;
1262             }});
1263     }
1264 
1265     /**
1266      * Method to find a named logger.
1267      * <p>
1268      * Note that since untrusted code may create loggers with
1269      * arbitrary names this method should not be relied on to
1270      * find Loggers for security sensitive logging.
1271      * It is also important to note that the Logger associated with the
1272      * String {@code name} may be garbage collected at any time if there
1273      * is no strong reference to the Logger. The caller of this method
1274      * must check the return value for null in order to properly handle
1275      * the case where the Logger has been garbage collected.
1276      *
1277      * @param name name of the logger
1278      * @return  matching logger or null if none is found
1279      */
1280     public Logger getLogger(String name) {
1281         return getUserContext().findLogger(name);
1282     }
1283 
1284     /**
1285      * Get an enumeration of known logger names.
1286      * <p>
1287      * Note:  Loggers may be added dynamically as new classes are loaded.
1288      * This method only reports on the loggers that are currently registered.
1289      * It is also important to note that this method only returns the name
1290      * of a Logger, not a strong reference to the Logger itself.
1291      * The returned String does nothing to prevent the Logger from being
1292      * garbage collected. In particular, if the returned name is passed
1293      * to {@code LogManager.getLogger()}, then the caller must check the
1294      * return value from {@code LogManager.getLogger()} for null to properly
1295      * handle the case where the Logger has been garbage collected in the
1296      * time since its name was returned by this method.
1297      *
1298      * @return  enumeration of logger name strings
1299      */
1300     public Enumeration<String> getLoggerNames() {
1301         return getUserContext().getLoggerNames();
1302     }
1303 
1304     /**
1305      * Reads and initializes the logging configuration.
1306      * <p>
1307      * If the "java.util.logging.config.class" system property is set, then the
1308      * property value is treated as a class name.  The given class will be
1309      * loaded, an object will be instantiated, and that object's constructor
1310      * is responsible for reading in the initial configuration.  (That object
1311      * may use other system properties to control its configuration.)  The
1312      * alternate configuration class can use {@code readConfiguration(InputStream)}
1313      * to define properties in the LogManager.
1314      * <p>
1315      * If "java.util.logging.config.class" system property is <b>not</b> set,
1316      * then this method will read the initial configuration from a properties
1317      * file and calls the {@link #readConfiguration(InputStream)} method to initialize
1318      * the configuration. The "java.util.logging.config.file" system property can be used
1319      * to specify the properties file that will be read as the initial configuration;
1320      * if not set, then the LogManager default configuration is used.
1321      * The default configuration is typically loaded from the
1322      * properties file "{@code conf/logging.properties}" in the Java installation
1323      * directory.
1324      *
1325      * <p>
1326      * Any {@linkplain #addConfigurationListener registered configuration
1327      * listener} will be invoked after the properties are read.
1328      *
1329      * @apiNote This {@code readConfiguration} method should only be used for
1330      * initializing the configuration during LogManager initialization or
1331      * used with the "java.util.logging.config.class" property.
1332      * When this method is called after loggers have been created, and
1333      * the "java.util.logging.config.class" system property is not set, all
1334      * existing loggers will be {@linkplain #reset() reset}. Then any
1335      * existing loggers that have a level property specified in the new
1336      * configuration stream will be {@linkplain
1337      * Logger#setLevel(java.util.logging.Level) set} to the specified log level.
1338      * <p>
1339      * To properly update the logging configuration, use the
1340      * {@link #updateConfiguration(java.util.function.Function)} or
1341      * {@link #updateConfiguration(java.io.InputStream, java.util.function.Function)}
1342      * methods instead.
1343      *
1344      * @throws   SecurityException  if a security manager exists and if
1345      *              the caller does not have LoggingPermission("control").
1346      * @throws   IOException if there are IO problems reading the configuration.
1347      */
1348     public void readConfiguration() throws IOException, SecurityException {
1349         checkPermission();
1350 
1351         // if a configuration class is specified, load it and use it.
1352         String cname = System.getProperty("java.util.logging.config.class");
1353         if (cname != null) {
1354             try {
1355                 // Instantiate the named class.  It is its constructor's
1356                 // responsibility to initialize the logging configuration, by
1357                 // calling readConfiguration(InputStream) with a suitable stream.
1358                 try {
1359                     Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(cname);
1360                     @SuppressWarnings("deprecation")
1361                     Object witness = clz.newInstance();
1362                     return;
1363                 } catch (ClassNotFoundException ex) {
1364                     Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(cname);
1365                     @SuppressWarnings("deprecation")
1366                     Object witness = clz.newInstance();
1367                     return;
1368                 }
1369             } catch (Exception ex) {
1370                 System.err.println("Logging configuration class \"" + cname + "\" failed");
1371                 System.err.println("" + ex);
1372                 // keep going and useful config file.
1373             }
1374         }
1375 
1376         String fname = getConfigurationFileName();
1377         try (final InputStream in = new FileInputStream(fname)) {
1378             final BufferedInputStream bin = new BufferedInputStream(in);
1379             readConfiguration(bin);
1380         }
1381     }
1382 
1383     String getConfigurationFileName() throws IOException {
1384         String fname = System.getProperty("java.util.logging.config.file");
1385         if (fname == null) {
1386             fname = System.getProperty("java.home");
1387             if (fname == null) {
1388                 throw new Error("Can't find java.home ??");
1389             }
1390             fname = Paths.get(fname, "conf", "logging.properties")
1391                     .toAbsolutePath().normalize().toString();
1392         }
1393         return fname;
1394     }
1395 
1396     /**
1397      * Reset the logging configuration.
1398      * <p>
1399      * For all named loggers, the reset operation removes and closes
1400      * all Handlers and (except for the root logger) sets the level
1401      * to {@code null}. The root logger's level is set to {@code Level.INFO}.
1402      *
1403      * @apiNote Calling this method also clears the LogManager {@linkplain
1404      * #getProperty(java.lang.String) properties}. The {@link
1405      * #updateConfiguration(java.util.function.Function)
1406      * updateConfiguration(Function)} or
1407      * {@link #updateConfiguration(java.io.InputStream, java.util.function.Function)
1408      * updateConfiguration(InputStream, Function)} method can be used to
1409      * properly update to a new configuration.
1410      *
1411      * @throws  SecurityException  if a security manager exists and if
1412      *             the caller does not have LoggingPermission("control").
1413      */
1414 
1415     public void reset() throws SecurityException {
1416         checkPermission();
1417 
1418         List<CloseOnReset> persistent;
1419 
1420         // We don't want reset() and readConfiguration()
1421         // to run in parallel
1422         configurationLock.lock();
1423         try {
1424             // install new empty properties
1425             props = new Properties();
1426             // make sure we keep the loggers persistent until reset is done.
1427             // Those are the loggers for which we previously created a
1428             // handler from the configuration, and we need to prevent them
1429             // from being gc'ed until those handlers are closed.
1430             persistent = new ArrayList<>(closeOnResetLoggers);
1431             closeOnResetLoggers.clear();
1432 
1433             // if reset has been called from shutdown-hook (Cleaner),
1434             // or if reset has been called from readConfiguration() which
1435             // already holds the lock and will change the state itself,
1436             // then do not change state here...
1437             if (globalHandlersState != STATE_SHUTDOWN &&
1438                 globalHandlersState != STATE_READING_CONFIG) {
1439                 // ...else user called reset()...
1440                 // Since we are doing a reset we no longer want to initialize
1441                 // the global handlers, if they haven't been initialized yet.
1442                 globalHandlersState = STATE_INITIALIZED;
1443             }
1444 
1445             for (LoggerContext cx : contexts()) {
1446                 resetLoggerContext(cx);
1447             }
1448 
1449             persistent.clear();
1450         } finally {
1451             configurationLock.unlock();
1452         }
1453     }
1454 
1455     private void resetLoggerContext(LoggerContext cx) {
1456         Enumeration<String> enum_ = cx.getLoggerNames();
1457         while (enum_.hasMoreElements()) {
1458             String name = enum_.nextElement();
1459             Logger logger = cx.findLogger(name);
1460             if (logger != null) {
1461                 resetLogger(logger);
1462             }
1463         }
1464     }
1465 
1466     private void closeHandlers(Logger logger) {
1467         Handler[] targets = logger.getHandlers();
1468         for (Handler h : targets) {
1469             logger.removeHandler(h);
1470             try {
1471                 h.close();
1472             } catch (Exception ex) {
1473                 // Problems closing a handler?  Keep going...
1474             } catch (Error e) {
1475                 // ignore Errors while shutting down
1476                 if (globalHandlersState != STATE_SHUTDOWN) {
1477                     throw e;
1478                 }
1479             }
1480         }
1481     }
1482 
1483     // Private method to reset an individual target logger.
1484     private void resetLogger(Logger logger) {
1485         // Close all the Logger handlers.
1486         closeHandlers(logger);
1487 
1488         // Reset Logger level
1489         String name = logger.getName();
1490         if (name != null && name.equals("")) {
1491             // This is the root logger.
1492             logger.setLevel(defaultLevel);
1493         } else {
1494             logger.setLevel(null);
1495         }
1496     }
1497 
1498     // get a list of whitespace separated classnames from a property.
1499     private String[] parseClassNames(String propertyName) {
1500         String hands = getProperty(propertyName);
1501         if (hands == null) {
1502             return new String[0];
1503         }
1504         hands = hands.trim();
1505         int ix = 0;
1506         final List<String> result = new ArrayList<>();
1507         while (ix < hands.length()) {
1508             int end = ix;
1509             while (end < hands.length()) {
1510                 if (Character.isWhitespace(hands.charAt(end))) {
1511                     break;
1512                 }
1513                 if (hands.charAt(end) == ',') {
1514                     break;
1515                 }
1516                 end++;
1517             }
1518             String word = hands.substring(ix, end);
1519             ix = end+1;
1520             word = word.trim();
1521             if (word.length() == 0) {
1522                 continue;
1523             }
1524             result.add(word);
1525         }
1526         return result.toArray(new String[result.size()]);
1527     }
1528 
1529     /**
1530      * Reads and initializes the logging configuration from the given input stream.
1531      *
1532      * <p>
1533      * Any {@linkplain #addConfigurationListener registered configuration
1534      * listener} will be invoked after the properties are read.
1535      *
1536      * @apiNote This {@code readConfiguration} method should only be used for
1537      * initializing the configuration during LogManager initialization or
1538      * used with the "java.util.logging.config.class" property.
1539      * When this method is called after loggers have been created, all
1540      * existing loggers will be {@linkplain #reset() reset}. Then any
1541      * existing loggers that have a level property specified in the
1542      * given input stream will be {@linkplain
1543      * Logger#setLevel(java.util.logging.Level) set} to the specified log level.
1544      * <p>
1545      * To properly update the logging configuration, use the
1546      * {@link #updateConfiguration(java.util.function.Function)} or
1547      * {@link #updateConfiguration(java.io.InputStream, java.util.function.Function)}
1548      * method instead.
1549      *
1550      * @param ins  stream to read properties from
1551      * @throws  SecurityException  if a security manager exists and if
1552      *             the caller does not have LoggingPermission("control").
1553      * @throws  IOException if there are problems reading from the stream,
1554      *             or the given stream is not in the
1555      *             {@linkplain java.util.Properties properties file} format.
1556      */
1557     public void readConfiguration(InputStream ins) throws IOException, SecurityException {
1558         checkPermission();
1559 
1560         // We don't want reset() and readConfiguration() to run
1561         // in parallel.
1562         configurationLock.lock();
1563         try {
1564             if (globalHandlersState == STATE_SHUTDOWN) {
1565                 // already in terminal state: don't even bother
1566                 // to read the configuration
1567                 return;
1568             }
1569 
1570             // change state to STATE_READING_CONFIG to signal reset() to not change it
1571             globalHandlersState = STATE_READING_CONFIG;
1572             try {
1573                 // reset configuration which leaves globalHandlersState at STATE_READING_CONFIG
1574                 // so that while reading configuration, any ongoing logging requests block and
1575                 // wait for the outcome (see the end of this try statement)
1576                 reset();
1577 
1578                 try {
1579                     // Load the properties
1580                     props.load(ins);
1581                 } catch (IllegalArgumentException x) {
1582                     // props.load may throw an IllegalArgumentException if the stream
1583                     // contains malformed Unicode escape sequences.
1584                     // We wrap that in an IOException as readConfiguration is
1585                     // specified to throw IOException if there are problems reading
1586                     // from the stream.
1587                     // Note: new IOException(x.getMessage(), x) allow us to get a more
1588                     // concise error message than new IOException(x);
1589                     throw new IOException(x.getMessage(), x);
1590                 }
1591 
1592                 // Instantiate new configuration objects.
1593                 String names[] = parseClassNames("config");
1594 
1595                 for (String word : names) {
1596                     try {
1597                         Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word);
1598                         @SuppressWarnings("deprecation")
1599                         Object witness = clz.newInstance();
1600                     } catch (Exception ex) {
1601                         System.err.println("Can't load config class \"" + word + "\"");
1602                         System.err.println("" + ex);
1603                         // ex.printStackTrace();
1604                     }
1605                 }
1606 
1607                 // Set levels on any pre-existing loggers, based on the new properties.
1608                 setLevelsOnExistingLoggers();
1609 
1610                 // Note that we need to reinitialize global handles when
1611                 // they are first referenced.
1612                 globalHandlersState = STATE_UNINITIALIZED;
1613             } catch (Throwable t) {
1614                 // If there were any trouble, then set state to STATE_INITIALIZED
1615                 // so that no global handlers reinitialization is performed on not fully
1616                 // initialized configuration.
1617                 globalHandlersState = STATE_INITIALIZED;
1618                 // re-throw
1619                 throw t;
1620             }
1621         } finally {
1622             configurationLock.unlock();
1623         }
1624 
1625         // should be called out of lock to avoid dead-lock situations
1626         // when user code is involved
1627         invokeConfigurationListeners();
1628     }
1629 
1630     // This enum enumerate the configuration properties that will be
1631     // updated on existing loggers when the configuration is updated
1632     // with LogManager.updateConfiguration().
1633     //
1634     // Note that this works properly only for the global LogManager - as
1635     // Handler and its subclasses get their configuration from
1636     // LogManager.getLogManager().
1637     //
1638     static enum ConfigProperty {
1639         LEVEL(".level"), HANDLERS(".handlers"), USEPARENT(".useParentHandlers");
1640         final String suffix;
1641         final int length;
1642         private ConfigProperty(String suffix) {
1643             this.suffix = Objects.requireNonNull(suffix);
1644             length = suffix.length();
1645         }
1646 
1647         public boolean handleKey(String key) {
1648             if (this == HANDLERS && suffix.substring(1).equals(key)) return true;
1649             if (this == HANDLERS && suffix.equals(key)) return false;
1650             return key.endsWith(suffix);
1651         }
1652         String key(String loggerName) {
1653             if (this == HANDLERS && (loggerName == null || loggerName.isEmpty())) {
1654                 return suffix.substring(1);
1655             }
1656             return loggerName + suffix;
1657         }
1658         String loggerName(String key) {
1659             assert key.equals(suffix.substring(1)) && this == HANDLERS || key.endsWith(suffix);
1660             if (this == HANDLERS && suffix.substring(1).equals(key)) return "";
1661             return key.substring(0, key.length() - length);
1662         }
1663 
1664         /**
1665          * If the property is one that should be updated on existing loggers by
1666          * updateConfiguration, returns the name of the logger for which the
1667          * property is configured. Otherwise, returns null.
1668          * @param property a property key in 'props'
1669          * @return the name of the logger on which the property is to be set,
1670          *         if the property is one that should be updated on existing
1671          *         loggers, {@code null} otherwise.
1672          */
1673         static String getLoggerName(String property) {
1674             for (ConfigProperty p : ConfigProperty.ALL) {
1675                 if (p.handleKey(property)) {
1676                     return p.loggerName(property);
1677                 }
1678             }
1679             return null; // Not a property that should be updated.
1680         }
1681 
1682         /**
1683          * Find the ConfigProperty corresponding to the given
1684          * property key (may find none).
1685          * @param property a property key in 'props'
1686          * @return An optional containing a ConfigProperty object,
1687          *         if the property is one that should be updated on existing
1688          *         loggers, empty otherwise.
1689          */
1690         static Optional<ConfigProperty> find(String property) {
1691             return ConfigProperty.ALL.stream()
1692                     .filter(p -> p.handleKey(property))
1693                     .findFirst();
1694          }
1695 
1696         /**
1697          * Returns true if the given property is one that should be updated
1698          * on existing loggers.
1699          * Used to filter property name streams.
1700          * @param property a property key from the configuration.
1701          * @return true if this property is of interest for updateConfiguration.
1702          */
1703         static boolean matches(String property) {
1704             return find(property).isPresent();
1705         }
1706 
1707         /**
1708          * Returns true if the new property value is different from the old,
1709          * and therefore needs to be updated on existing loggers.
1710          * @param k a property key in the configuration
1711          * @param previous the old configuration
1712          * @param next the new configuration
1713          * @return true if the property is changing value between the two
1714          *         configurations.
1715          */
1716         static boolean needsUpdating(String k, Properties previous, Properties next) {
1717             final String p = trim(previous.getProperty(k, null));
1718             final String n = trim(next.getProperty(k, null));
1719             return ! Objects.equals(p,n);
1720         }
1721 
1722         /**
1723          * Applies the mapping function for the given key to the next
1724          * configuration.
1725          * If the mapping function is null then this method does nothing.
1726          * Otherwise, it calls the mapping function to compute the value
1727          * that should be associated with {@code key} in the resulting
1728          * configuration, and applies it to {@code next}.
1729          * If the mapping function returns {@code null} the key is removed
1730          * from {@code next}.
1731          *
1732          * @param k a property key in the configuration
1733          * @param previous the old configuration
1734          * @param next the new configuration (modified by this function)
1735          * @param mappingFunction the mapping function.
1736          */
1737         static void merge(String k, Properties previous, Properties next,
1738                           BiFunction<String, String, String> mappingFunction) {
1739             String p = trim(previous.getProperty(k, null));
1740             String n = trim(next.getProperty(k, null));
1741             String mapped = trim(mappingFunction.apply(p,n));
1742             if (!Objects.equals(n, mapped)) {
1743                 if (mapped == null) {
1744                     next.remove(k);
1745                 } else {
1746                     next.setProperty(k, mapped);
1747                 }
1748             }
1749         }
1750 
1751         private static final EnumSet<ConfigProperty> ALL =
1752                 EnumSet.allOf(ConfigProperty.class);
1753     }
1754 
1755     // trim the value if not null.
1756     private static String trim(String value) {
1757         return value == null ? null : value.trim();
1758     }
1759 
1760     /**
1761      * An object that keep track of loggers we have already visited.
1762      * Used when updating configuration, to avoid processing the same logger
1763      * twice.
1764      */
1765     static final class VisitedLoggers implements Predicate<Logger> {
1766         final IdentityHashMap<Logger,Boolean> visited;
1767         private VisitedLoggers(IdentityHashMap<Logger,Boolean> visited) {
1768             this.visited = visited;
1769         }
1770         VisitedLoggers() {
1771             this(new IdentityHashMap<>());
1772         }
1773         @Override
1774         public boolean test(Logger logger) {
1775             return visited != null && visited.put(logger, Boolean.TRUE) != null;
1776         }
1777         public void clear() {
1778             if (visited != null) visited.clear();
1779         }
1780 
1781         // An object that considers that no logger has ever been visited.
1782         // This is used when processParentHandlers is called from
1783         // LoggerContext.addLocalLogger
1784         static final VisitedLoggers NEVER = new VisitedLoggers(null);
1785     }
1786 
1787 
1788     /**
1789      * Type of the modification for a given property. One of SAME, ADDED, CHANGED,
1790      * or REMOVED.
1791      */
1792     static enum ModType {
1793         SAME,    // property had no value in the old and new conf, or had the
1794                  // same value in both.
1795         ADDED,   // property had no value in the old conf, but has one in the new.
1796         CHANGED, // property has a different value in the old conf and the new conf.
1797         REMOVED; // property has no value in the new conf, but had one in the old.
1798         static ModType of(String previous, String next) {
1799             if (previous == null && next != null) {
1800                 return ADDED;
1801             }
1802             if (next == null && previous != null) {
1803                 return REMOVED;
1804             }
1805             if (!Objects.equals(trim(previous), trim(next))) {
1806                 return CHANGED;
1807             }
1808             return SAME;
1809         }
1810     }
1811 
1812     /**
1813      * Updates the logging configuration.
1814      * <p>
1815      * If the "java.util.logging.config.file" system property is set,
1816      * then the property value specifies the properties file to be read
1817      * as the new configuration. Otherwise, the LogManager default
1818      * configuration is used.
1819      * <br>The default configuration is typically loaded from the
1820      * properties file "{@code conf/logging.properties}" in the
1821      * Java installation directory.
1822      * <p>
1823      * This method reads the new configuration and calls the {@link
1824      * #updateConfiguration(java.io.InputStream, java.util.function.Function)
1825      * updateConfiguration(ins, mapper)} method to
1826      * update the configuration.
1827      *
1828      * @apiNote
1829      * This method updates the logging configuration from reading
1830      * a properties file and ignores the "java.util.logging.config.class"
1831      * system property.  The "java.util.logging.config.class" property is
1832      * only used by the {@link #readConfiguration()}  method to load a custom
1833      * configuration class as an initial configuration.
1834      *
1835      * @param mapper a functional interface that takes a configuration
1836      *   key <i>k</i> and returns a function <i>f(o,n)</i> whose returned
1837      *   value will be applied to the resulting configuration. The
1838      *   function <i>f</i> may return {@code null} to indicate that the property
1839      *   <i>k</i> will not be added to the resulting configuration.
1840      *   <br>
1841      *   If {@code mapper} is {@code null} then {@code (k) -> ((o, n) -> n)} is
1842      *   assumed.
1843      *   <br>
1844      *   For each <i>k</i>, the mapped function <i>f</i> will
1845      *   be invoked with the value associated with <i>k</i> in the old
1846      *   configuration (i.e <i>o</i>) and the value associated with
1847      *   <i>k</i> in the new configuration (i.e. <i>n</i>).
1848      *   <br>A {@code null} value for <i>o</i> or <i>n</i> indicates that no
1849      *   value was present for <i>k</i> in the corresponding configuration.
1850      *
1851      * @throws  SecurityException  if a security manager exists and if
1852      *          the caller does not have LoggingPermission("control"), or
1853      *          does not have the permissions required to set up the
1854      *          configuration (e.g. open file specified for FileHandlers
1855      *          etc...)
1856      *
1857      * @throws  NullPointerException  if {@code mapper} returns a {@code null}
1858      *         function when invoked.
1859      *
1860      * @throws  IOException if there are problems reading from the
1861      *          logging configuration file.
1862      *
1863      * @see #updateConfiguration(java.io.InputStream, java.util.function.Function)
1864      * @since 9
1865      */
1866     public void updateConfiguration(Function<String, BiFunction<String,String,String>> mapper)
1867             throws IOException {
1868         checkPermission();
1869         ensureLogManagerInitialized();
1870         drainLoggerRefQueueBounded();
1871 
1872         String fname = getConfigurationFileName();
1873         try (final InputStream in = new FileInputStream(fname)) {
1874             final BufferedInputStream bin = new BufferedInputStream(in);
1875             updateConfiguration(bin, mapper);
1876         }
1877     }
1878 
1879     /**
1880      * Updates the logging configuration.
1881      * <p>
1882      * For each configuration key in the {@linkplain
1883      * #getProperty(java.lang.String) existing configuration} and
1884      * the given input stream configuration, the given {@code mapper} function
1885      * is invoked to map from the configuration key to a function,
1886      * <i>f(o,n)</i>, that takes the old value and new value and returns
1887      * the resulting value to be applied in the resulting configuration,
1888      * as specified in the table below.
1889      * <p>Let <i>k</i> be a configuration key in the old or new configuration,
1890      * <i>o</i> be the old value (i.e. the value associated
1891      * with <i>k</i> in the old configuration), <i>n</i> be the
1892      * new value (i.e. the value associated with <i>k</i> in the new
1893      * configuration), and <i>f</i> be the function returned
1894      * by {@code mapper.apply(}<i>k</i>{@code )}: then <i>v = f(o,n)</i> is the
1895      * resulting value. If <i>v</i> is not {@code null}, then a property
1896      * <i>k</i> with value <i>v</i> will be added to the resulting configuration.
1897      * Otherwise, it will be omitted.
1898      * <br>A {@code null} value may be passed to function
1899      * <i>f</i> to indicate that the corresponding configuration has no
1900      * configuration key <i>k</i>.
1901      * The function <i>f</i> may return {@code null} to indicate that
1902      * there will be no value associated with <i>k</i> in the resulting
1903      * configuration.
1904      * <p>
1905      * If {@code mapper} is {@code null}, then <i>v</i> will be set to
1906      * <i>n</i>.
1907      * <p>
1908      * LogManager {@linkplain #getProperty(java.lang.String) properties} are
1909      * updated with the resulting value in the resulting configuration.
1910      * <p>
1911      * The registered {@linkplain #addConfigurationListener configuration
1912      * listeners} will be invoked after the configuration is successfully updated.
1913      * <br><br>
1914      * <table class="striped">
1915      * <caption style="display:none">Updating configuration properties</caption>
1916      * <thead>
1917      * <tr>
1918      * <th scope="col">Property</th>
1919      * <th scope="col">Resulting Behavior</th>
1920      * </tr>
1921      * </thead>
1922      * <tbody>
1923      * <tr>
1924      * <th scope="row" valign="top">{@code <logger>.level}</th>
1925      * <td>
1926      * <ul>
1927      *   <li>If the resulting configuration defines a level for a logger and
1928      *       if the resulting level is different than the level specified in the
1929      *       the old configuration, or not specified in
1930      *       the old configuration, then if the logger exists or if children for
1931      *       that logger exist, the level for that logger will be updated,
1932      *       and the change propagated to any existing logger children.
1933      *       This may cause the logger to be created, if necessary.
1934      *   </li>
1935      *   <li>If the old configuration defined a level for a logger, and the
1936      *       resulting configuration doesn't, then this change will not be
1937      *       propagated to existing loggers, if any.
1938      *       To completely replace a configuration - the caller should therefore
1939      *       call {@link #reset() reset} to empty the current configuration,
1940      *       before calling {@code updateConfiguration}.
1941      *   </li>
1942      * </ul>
1943      * </td>
1944      * <tr>
1945      * <th scope="row" valign="top">{@code <logger>.useParentHandlers}</th>
1946      * <td>
1947      * <ul>
1948      *   <li>If either the resulting or the old value for the useParentHandlers
1949      *       property is not null, then if the logger exists or if children for
1950      *       that logger exist, that logger will be updated to the resulting
1951      *       value.
1952      *       The value of the useParentHandlers property is the value specified
1953      *       in the configuration; if not specified, the default is true.
1954      *   </li>
1955      * </ul>
1956      * </td>
1957      * </tr>
1958      * <tr>
1959      * <th scope="row" valign="top">{@code <logger>.handlers}</th>
1960      * <td>
1961      * <ul>
1962      *   <li>If the resulting configuration defines a list of handlers for a
1963      *       logger, and if the resulting list is different than the list
1964      *       specified in the old configuration for that logger (that could be
1965      *       empty), then if the logger exists or its children exist, the
1966      *       handlers associated with that logger are closed and removed and
1967      *       the new handlers will be created per the resulting configuration
1968      *       and added to that logger, creating that logger if necessary.
1969      *   </li>
1970      *   <li>If the old configuration defined some handlers for a logger, and
1971      *       the resulting configuration doesn't, if that logger exists,
1972      *       its handlers will be removed and closed.
1973      *   </li>
1974      *   <li>Changing the list of handlers on an existing logger will cause all
1975      *       its previous handlers to be removed and closed, regardless of whether
1976      *       they had been created from the configuration or programmatically.
1977      *       The old handlers will be replaced by new handlers, if any.
1978      *   </li>
1979      * </ul>
1980      * </td>
1981      * </tr>
1982      * <tr>
1983      * <th scope="row" valign="top">{@code <handler-name>.*}</th>
1984      * <td>
1985      * <ul>
1986      *   <li>Properties configured/changed on handler classes will only affect
1987      *       newly created handlers. If a node is configured with the same list
1988      *       of handlers in the old and the resulting configuration, then these
1989      *       handlers will remain unchanged.
1990      *   </li>
1991      * </ul>
1992      * </td>
1993      * </tr>
1994      * <tr>
1995      * <th scope="row" valign="top">{@code config} and any other property</th>
1996      * <td>
1997      * <ul>
1998      *   <li>The resulting value for these property will be stored in the
1999      *   LogManager properties, but {@code updateConfiguration} will not parse
2000      *   or process their values.
2001      *   </li>
2002      * </ul>
2003      * </td>
2004      * </tr>
2005      * </tbody>
2006      * </table>
2007      * <p>
2008      * <em>Example mapper functions:</em>
2009      * <br><br>
2010      * <ul>
2011      * <li>Replace all logging properties with the new configuration:
2012      * <br><br>{@code     (k) -> ((o, n) -> n)}:
2013      * <br><br>this is equivalent to passing a null {@code mapper} parameter.
2014      * </li>
2015      * <li>Merge the new configuration and old configuration and use the
2016      * new value if <i>k</i> exists in the new configuration:
2017      * <br><br>{@code     (k) -> ((o, n) -> n == null ? o : n)}:
2018      * <br><br>as if merging two collections as follows:
2019      * {@code result.putAll(oldc); result.putAll(newc)}.<br></li>
2020      * <li>Merge the new configuration and old configuration and use the old
2021      * value if <i>k</i> exists in the old configuration:
2022      * <br><br>{@code     (k) -> ((o, n) -> o == null ? n : o)}:
2023      * <br><br>as if merging two collections as follows:
2024      * {@code result.putAll(newc); result.putAll(oldc)}.<br></li>
2025      * <li>Replace all properties with the new configuration except the handler
2026      * property to configure Logger's handler that is not root logger:
2027      * <br>
2028      * <pre>{@code (k) -> k.endsWith(".handlers")}
2029      *      {@code     ? ((o, n) -> (o == null ? n : o))}
2030      *      {@code     : ((o, n) -> n)}</pre>
2031      * </li>
2032      * </ul>
2033      * <p>
2034      * To completely reinitialize a configuration, an application can first call
2035      * {@link #reset() reset} to fully remove the old configuration, followed by
2036      * {@code updateConfiguration} to initialize the new configuration.
2037      *
2038      * @param ins    a stream to read properties from
2039      * @param mapper a functional interface that takes a configuration
2040      *   key <i>k</i> and returns a function <i>f(o,n)</i> whose returned
2041      *   value will be applied to the resulting configuration. The
2042      *   function <i>f</i> may return {@code null} to indicate that the property
2043      *   <i>k</i> will not be added to the resulting configuration.
2044      *   <br>
2045      *   If {@code mapper} is {@code null} then {@code (k) -> ((o, n) -> n)} is
2046      *   assumed.
2047      *   <br>
2048      *   For each <i>k</i>, the mapped function <i>f</i> will
2049      *   be invoked with the value associated with <i>k</i> in the old
2050      *   configuration (i.e <i>o</i>) and the value associated with
2051      *   <i>k</i> in the new configuration (i.e. <i>n</i>).
2052      *   <br>A {@code null} value for <i>o</i> or <i>n</i> indicates that no
2053      *   value was present for <i>k</i> in the corresponding configuration.
2054      *
2055      * @throws  SecurityException if a security manager exists and if
2056      *          the caller does not have LoggingPermission("control"), or
2057      *          does not have the permissions required to set up the
2058      *          configuration (e.g. open files specified for FileHandlers)
2059      *
2060      * @throws  NullPointerException if {@code ins} is null or if
2061      *          {@code mapper} returns a null function when invoked.
2062      *
2063      * @throws  IOException if there are problems reading from the stream,
2064      *          or the given stream is not in the
2065      *          {@linkplain java.util.Properties properties file} format.
2066      * @since 9
2067      */
2068     public void updateConfiguration(InputStream ins,
2069             Function<String, BiFunction<String,String,String>> mapper)
2070             throws IOException {
2071         checkPermission();
2072         ensureLogManagerInitialized();
2073         drainLoggerRefQueueBounded();
2074 
2075         final Properties previous;
2076         final Set<String> updatePropertyNames;
2077         List<LoggerContext> cxs = Collections.emptyList();
2078         final VisitedLoggers visited = new VisitedLoggers();
2079         final Properties next = new Properties();
2080 
2081         try {
2082             // Load the properties
2083             next.load(ins);
2084         } catch (IllegalArgumentException x) {
2085             // props.load may throw an IllegalArgumentException if the stream
2086             // contains malformed Unicode escape sequences.
2087             // We wrap that in an IOException as updateConfiguration is
2088             // specified to throw IOException if there are problems reading
2089             // from the stream.
2090             // Note: new IOException(x.getMessage(), x) allow us to get a more
2091             // concise error message than new IOException(x);
2092             throw new IOException(x.getMessage(), x);
2093         }
2094 
2095         if (globalHandlersState == STATE_SHUTDOWN) return;
2096 
2097         // exclusive lock: readConfiguration/reset/updateConfiguration can't
2098         //           run concurrently.
2099         // configurationLock.writeLock().lock();
2100         configurationLock.lock();
2101         try {
2102             if (globalHandlersState == STATE_SHUTDOWN) return;
2103             previous = props;
2104 
2105             // Builds a TreeSet of all (old and new) property names.
2106             updatePropertyNames =
2107                     Stream.concat(previous.stringPropertyNames().stream(),
2108                                   next.stringPropertyNames().stream())
2109                         .collect(Collectors.toCollection(TreeSet::new));
2110 
2111             if (mapper != null) {
2112                 // mapper will potentially modify the content of
2113                 // 'next', so we need to call it before affecting props=next.
2114                 // give a chance to the mapper to control all
2115                 // properties - not just those we will reset.
2116                 updatePropertyNames.stream()
2117                         .forEachOrdered(k -> ConfigProperty
2118                                 .merge(k, previous, next,
2119                                        Objects.requireNonNull(mapper.apply(k))));
2120             }
2121 
2122             props = next;
2123 
2124             // allKeys will contain all keys:
2125             //    - which correspond to a configuration property we are interested in
2126             //      (first filter)
2127             //    - whose value needs to be updated (because it's new, removed, or
2128             //      different) in the resulting configuration (second filter)
2129             final Stream<String> allKeys = updatePropertyNames.stream()
2130                     .filter(ConfigProperty::matches)
2131                     .filter(k -> ConfigProperty.needsUpdating(k, previous, next));
2132 
2133             // Group configuration properties by logger name
2134             // We use a TreeMap so that parent loggers will be visited before
2135             // child loggers.
2136             final Map<String, TreeSet<String>> loggerConfigs =
2137                     allKeys.collect(Collectors.groupingBy(ConfigProperty::getLoggerName,
2138                                     TreeMap::new,
2139                                     Collectors.toCollection(TreeSet::new)));
2140 
2141             if (!loggerConfigs.isEmpty()) {
2142                 cxs = contexts();
2143             }
2144             final List<Logger> loggers = cxs.isEmpty()
2145                     ? Collections.emptyList() : new ArrayList<>(cxs.size());
2146             for (Map.Entry<String, TreeSet<String>> e : loggerConfigs.entrySet()) {
2147                 // This can be a logger name, or something else...
2148                 // The only thing we know is that we found a property
2149                 //    we are interested in.
2150                 // For instance, if we found x.y.z.level, then x.y.z could be
2151                 // a logger, but it could also be a handler class...
2152                 // Anyway...
2153                 final String name = e.getKey();
2154                 final Set<String> properties = e.getValue();
2155                 loggers.clear();
2156                 for (LoggerContext cx : cxs) {
2157                     Logger l = cx.findLogger(name);
2158                     if (l != null && !visited.test(l)) {
2159                         loggers.add(l);
2160                     }
2161                 }
2162                 if (loggers.isEmpty()) continue;
2163                 for (String pk : properties) {
2164                     ConfigProperty cp = ConfigProperty.find(pk).get();
2165                     String p = previous.getProperty(pk, null);
2166                     String n = next.getProperty(pk, null);
2167 
2168                     // Determines the type of modification.
2169                     ModType mod = ModType.of(p, n);
2170 
2171                     // mod == SAME means that the two values are equals, there
2172                     // is nothing to do. Usually, this should not happen as such
2173                     // properties should have been filtered above.
2174                     // It could happen however if the properties had
2175                     // trailing/leading whitespaces.
2176                     if (mod == ModType.SAME) continue;
2177 
2178                     switch (cp) {
2179                         case LEVEL:
2180                             if (mod == ModType.REMOVED) continue;
2181                             Level level = Level.findLevel(trim(n));
2182                             if (level != null) {
2183                                 if (name.isEmpty()) {
2184                                     rootLogger.setLevel(level);
2185                                 }
2186                                 for (Logger l : loggers) {
2187                                     if (!name.isEmpty() || l != rootLogger) {
2188                                         l.setLevel(level);
2189                                     }
2190                                 }
2191                             }
2192                             break;
2193                         case USEPARENT:
2194                             if (!name.isEmpty()) {
2195                                 boolean useParent = getBooleanProperty(pk, true);
2196                                 if (n != null || p != null) {
2197                                     // reset the flag only if the previous value
2198                                     // or the new value are not null.
2199                                     for (Logger l : loggers) {
2200                                         l.setUseParentHandlers(useParent);
2201                                     }
2202                                 }
2203                             }
2204                             break;
2205                         case HANDLERS:
2206                             List<Handler> hdls = null;
2207                             if (name.isEmpty()) {
2208                                 // special handling for the root logger.
2209                                 globalHandlersState = STATE_READING_CONFIG;
2210                                 try {
2211                                     closeHandlers(rootLogger);
2212                                     globalHandlersState = STATE_UNINITIALIZED;
2213                                 } catch (Throwable t) {
2214                                     globalHandlersState = STATE_INITIALIZED;
2215                                     throw t;
2216                                 }
2217                             }
2218                             for (Logger l : loggers) {
2219                                 if (l == rootLogger) continue;
2220                                 closeHandlers(l);
2221                                 if (mod == ModType.REMOVED) {
2222                                     closeOnResetLoggers.removeIf(c -> c.logger == l);
2223                                     continue;
2224                                 }
2225                                 if (hdls == null) {
2226                                     hdls = name.isEmpty()
2227                                             ? Arrays.asList(rootLogger.getHandlers())
2228                                             : createLoggerHandlers(name, pk);
2229                                 }
2230                                 setLoggerHandlers(l, name, pk, hdls);
2231                             }
2232                             break;
2233                         default: break;
2234                     }
2235                 }
2236             }
2237         } finally {
2238             configurationLock.unlock();
2239             visited.clear();
2240         }
2241 
2242         // Now ensure that if an existing logger has acquired a new parent
2243         // in the configuration, this new parent will be created - if needed,
2244         // and added to the context of the existing child.
2245         //
2246         drainLoggerRefQueueBounded();
2247         for (LoggerContext cx : cxs) {
2248             for (Enumeration<String> names = cx.getLoggerNames() ; names.hasMoreElements();) {
2249                 String name = names.nextElement();
2250                 if (name.isEmpty()) continue;  // don't need to process parents on root.
2251                 Logger l = cx.findLogger(name);
2252                 if (l != null && !visited.test(l)) {
2253                     // should pass visited here to cut the processing when
2254                     // reaching a logger already visited.
2255                     cx.processParentHandlers(l, name, visited);
2256                 }
2257             }
2258         }
2259 
2260         // We changed the configuration: invoke configuration listeners
2261         invokeConfigurationListeners();
2262     }
2263 
2264     /**
2265      * Get the value of a logging property.
2266      * The method returns null if the property is not found.
2267      * @param name      property name
2268      * @return          property value
2269      */
2270     public String getProperty(String name) {
2271         return props.getProperty(name);
2272     }
2273 
2274     // Package private method to get a String property.
2275     // If the property is not defined we return the given
2276     // default value.
2277     String getStringProperty(String name, String defaultValue) {
2278         String val = getProperty(name);
2279         if (val == null) {
2280             return defaultValue;
2281         }
2282         return val.trim();
2283     }
2284 
2285     // Package private method to get an integer property.
2286     // If the property is not defined or cannot be parsed
2287     // we return the given default value.
2288     int getIntProperty(String name, int defaultValue) {
2289         String val = getProperty(name);
2290         if (val == null) {
2291             return defaultValue;
2292         }
2293         try {
2294             return Integer.parseInt(val.trim());
2295         } catch (Exception ex) {
2296             return defaultValue;
2297         }
2298     }
2299 
2300     // Package private method to get a long property.
2301     // If the property is not defined or cannot be parsed
2302     // we return the given default value.
2303     long getLongProperty(String name, long defaultValue) {
2304         String val = getProperty(name);
2305         if (val == null) {
2306             return defaultValue;
2307         }
2308         try {
2309             return Long.parseLong(val.trim());
2310         } catch (Exception ex) {
2311             return defaultValue;
2312         }
2313     }
2314 
2315     // Package private method to get a boolean property.
2316     // If the property is not defined or cannot be parsed
2317     // we return the given default value.
2318     boolean getBooleanProperty(String name, boolean defaultValue) {
2319         String val = getProperty(name);
2320         if (val == null) {
2321             return defaultValue;
2322         }
2323         val = val.toLowerCase();
2324         if (val.equals("true") || val.equals("1")) {
2325             return true;
2326         } else if (val.equals("false") || val.equals("0")) {
2327             return false;
2328         }
2329         return defaultValue;
2330     }
2331 
2332     // Package private method to get a Level property.
2333     // If the property is not defined or cannot be parsed
2334     // we return the given default value.
2335     Level getLevelProperty(String name, Level defaultValue) {
2336         String val = getProperty(name);
2337         if (val == null) {
2338             return defaultValue;
2339         }
2340         Level l = Level.findLevel(val.trim());
2341         return l != null ? l : defaultValue;
2342     }
2343 
2344     // Package private method to get a filter property.
2345     // We return an instance of the class named by the "name"
2346     // property. If the property is not defined or has problems
2347     // we return the defaultValue.
2348     Filter getFilterProperty(String name, Filter defaultValue) {
2349         String val = getProperty(name);
2350         try {
2351             if (val != null) {
2352                 @SuppressWarnings("deprecation")
2353                 Object o = ClassLoader.getSystemClassLoader().loadClass(val).newInstance();
2354                 return (Filter) o;
2355             }
2356         } catch (Exception ex) {
2357             // We got one of a variety of exceptions in creating the
2358             // class or creating an instance.
2359             // Drop through.
2360         }
2361         // We got an exception.  Return the defaultValue.
2362         return defaultValue;
2363     }
2364 
2365 
2366     // Package private method to get a formatter property.
2367     // We return an instance of the class named by the "name"
2368     // property. If the property is not defined or has problems
2369     // we return the defaultValue.
2370     Formatter getFormatterProperty(String name, Formatter defaultValue) {
2371         String val = getProperty(name);
2372         try {
2373             if (val != null) {
2374                 @SuppressWarnings("deprecation")
2375                 Object o = ClassLoader.getSystemClassLoader().loadClass(val).newInstance();
2376                 return (Formatter) o;
2377             }
2378         } catch (Exception ex) {
2379             // We got one of a variety of exceptions in creating the
2380             // class or creating an instance.
2381             // Drop through.
2382         }
2383         // We got an exception.  Return the defaultValue.
2384         return defaultValue;
2385     }
2386 
2387     // Private method to load the global handlers.
2388     // We do the real work lazily, when the global handlers
2389     // are first used.
2390     private void initializeGlobalHandlers() {
2391         int state = globalHandlersState;
2392         if (state == STATE_INITIALIZED ||
2393             state == STATE_SHUTDOWN) {
2394             // Nothing to do: return.
2395             return;
2396         }
2397 
2398         // If we have not initialized global handlers yet (or need to
2399         // reinitialize them), lets do it now (this case is indicated by
2400         // globalHandlersState == STATE_UNINITIALIZED).
2401         // If we are in the process of initializing global handlers we
2402         // also need to lock & wait (this case is indicated by
2403         // globalHandlersState == STATE_INITIALIZING).
2404         // If we are in the process of reading configuration we also need to
2405         // wait to see what the outcome will be (this case
2406         // is indicated by globalHandlersState == STATE_READING_CONFIG)
2407         // So in either case we need to wait for the lock.
2408         configurationLock.lock();
2409         try {
2410             if (globalHandlersState != STATE_UNINITIALIZED) {
2411                 return; // recursive call or nothing to do
2412             }
2413             // set globalHandlersState to STATE_INITIALIZING first to avoid
2414             // getting an infinite recursion when loadLoggerHandlers(...)
2415             // is going to call addHandler(...)
2416             globalHandlersState = STATE_INITIALIZING;
2417             try {
2418                 loadLoggerHandlers(rootLogger, null, "handlers");
2419             } finally {
2420                 globalHandlersState = STATE_INITIALIZED;
2421             }
2422         } finally {
2423             configurationLock.unlock();
2424         }
2425     }
2426 
2427     static final Permission controlPermission =
2428             new LoggingPermission("control", null);
2429 
2430     void checkPermission() {
2431         SecurityManager sm = System.getSecurityManager();
2432         if (sm != null)
2433             sm.checkPermission(controlPermission);
2434     }
2435 
2436     /**
2437      * Check that the current context is trusted to modify the logging
2438      * configuration.  This requires LoggingPermission("control").
2439      * <p>
2440      * If the check fails we throw a SecurityException, otherwise
2441      * we return normally.
2442      *
2443      * @exception  SecurityException  if a security manager exists and if
2444      *             the caller does not have LoggingPermission("control").
2445      */
2446     public void checkAccess() throws SecurityException {
2447         checkPermission();
2448     }
2449 
2450     // Nested class to represent a node in our tree of named loggers.
2451     private static class LogNode {
2452         HashMap<String,LogNode> children;
2453         LoggerWeakRef loggerRef;
2454         LogNode parent;
2455         final LoggerContext context;
2456 
2457         LogNode(LogNode parent, LoggerContext context) {
2458             this.parent = parent;
2459             this.context = context;
2460         }
2461 
2462         // Recursive method to walk the tree below a node and set
2463         // a new parent logger.
2464         void walkAndSetParent(Logger parent) {
2465             if (children == null) {
2466                 return;
2467             }
2468             for (LogNode node : children.values()) {
2469                 LoggerWeakRef ref = node.loggerRef;
2470                 Logger logger = (ref == null) ? null : ref.get();
2471                 if (logger == null) {
2472                     node.walkAndSetParent(parent);
2473                 } else {
2474                     doSetParent(logger, parent);
2475                 }
2476             }
2477         }
2478     }
2479 
2480     // We use a subclass of Logger for the root logger, so
2481     // that we only instantiate the global handlers when they
2482     // are first needed.
2483     private final class RootLogger extends Logger {
2484         private RootLogger() {
2485             // We do not call the protected Logger two args constructor here,
2486             // to avoid calling LogManager.getLogManager() from within the
2487             // RootLogger constructor.
2488             super("", null, null, LogManager.this, true);
2489         }
2490 
2491         @Override
2492         public void log(LogRecord record) {
2493             // Make sure that the global handlers have been instantiated.
2494             initializeGlobalHandlers();
2495             super.log(record);
2496         }
2497 
2498         @Override
2499         public void addHandler(Handler h) {
2500             initializeGlobalHandlers();
2501             super.addHandler(h);
2502         }
2503 
2504         @Override
2505         public void removeHandler(Handler h) {
2506             initializeGlobalHandlers();
2507             super.removeHandler(h);
2508         }
2509 
2510         @Override
2511         Handler[] accessCheckedHandlers() {
2512             initializeGlobalHandlers();
2513             return super.accessCheckedHandlers();
2514         }
2515     }
2516 
2517 
2518     // Private method to be called when the configuration has
2519     // changed to apply any level settings to any pre-existing loggers.
2520     private void setLevelsOnExistingLoggers() {
2521         Enumeration<?> enum_ = props.propertyNames();
2522         while (enum_.hasMoreElements()) {
2523             String key = (String)enum_.nextElement();
2524             if (!key.endsWith(".level")) {
2525                 // Not a level definition.
2526                 continue;
2527             }
2528             int ix = key.length() - 6;
2529             String name = key.substring(0, ix);
2530             Level level = getLevelProperty(key, null);
2531             if (level == null) {
2532                 System.err.println("Bad level value for property: " + key);
2533                 continue;
2534             }
2535             for (LoggerContext cx : contexts()) {
2536                 Logger l = cx.findLogger(name);
2537                 if (l == null) {
2538                     continue;
2539                 }
2540                 l.setLevel(level);
2541             }
2542         }
2543     }
2544 
2545     /**
2546      * String representation of the
2547      * {@link javax.management.ObjectName} for the management interface
2548      * for the logging facility.
2549      *
2550      * @see java.lang.management.PlatformLoggingMXBean
2551      *
2552      * @since 1.5
2553      */
2554     public final static String LOGGING_MXBEAN_NAME
2555         = "java.util.logging:type=Logging";
2556 
2557     /**
2558      * Returns {@code LoggingMXBean} for managing loggers.
2559      *
2560      * @return a {@link LoggingMXBean} object.
2561      *
2562      * @deprecated {@code java.util.logging.LoggingMXBean} is deprecated and
2563      *      replaced with {@code java.lang.management.PlatformLoggingMXBean}. Use
2564      *      {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
2565      *      ManagementFactory.getPlatformMXBean}(PlatformLoggingMXBean.class)
2566      *      instead.
2567      *
2568      * @see java.lang.management.PlatformLoggingMXBean
2569      * @since 1.5
2570      */
2571     @Deprecated(since="9")
2572     public static synchronized LoggingMXBean getLoggingMXBean() {
2573         return Logging.getInstance();
2574     }
2575 
2576     /**
2577      * Adds a configuration listener to be invoked each time the logging
2578      * configuration is read.
2579      * If the listener is already registered the method does nothing.
2580      * <p>
2581      * The listener is invoked with privileges that are restricted by the
2582      * calling context of this method.
2583      * The order in which the listeners are invoked is unspecified.
2584      * <p>
2585      * It is recommended that listeners do not throw errors or exceptions.
2586      *
2587      * If a listener terminates with an uncaught error or exception then
2588      * the first exception will be propagated to the caller of
2589      * {@link #readConfiguration()} (or {@link #readConfiguration(java.io.InputStream)})
2590      * after all listeners have been invoked.
2591      *
2592      * @implNote If more than one listener terminates with an uncaught error or
2593      * exception, an implementation may record the additional errors or
2594      * exceptions as {@linkplain Throwable#addSuppressed(java.lang.Throwable)
2595      * suppressed exceptions}.
2596      *
2597      * @param listener A configuration listener that will be invoked after the
2598      *        configuration changed.
2599      * @return This LogManager.
2600      * @throws SecurityException if a security manager exists and if the
2601      * caller does not have LoggingPermission("control").
2602      * @throws NullPointerException if the listener is null.
2603      *
2604      * @since 9
2605      */
2606     public LogManager addConfigurationListener(Runnable listener) {
2607         final Runnable r = Objects.requireNonNull(listener);
2608         checkPermission();
2609         final SecurityManager sm = System.getSecurityManager();
2610         final AccessControlContext acc =
2611                 sm == null ? null : AccessController.getContext();
2612         final PrivilegedAction<Void> pa =
2613                 acc == null ? null : () -> { r.run() ; return null; };
2614         final Runnable pr =
2615                 acc == null ? r : () -> AccessController.doPrivileged(pa, acc);
2616         // Will do nothing if already registered.
2617         listeners.putIfAbsent(r, pr);
2618         return this;
2619     }
2620 
2621     /**
2622      * Removes a previously registered configuration listener.
2623      *
2624      * Returns silently if the listener is not found.
2625      *
2626      * @param listener the configuration listener to remove.
2627      * @throws NullPointerException if the listener is null.
2628      * @throws SecurityException if a security manager exists and if the
2629      * caller does not have LoggingPermission("control").
2630      *
2631      * @since 9
2632      */
2633     public void removeConfigurationListener(Runnable listener) {
2634         final Runnable key = Objects.requireNonNull(listener);
2635         checkPermission();
2636         listeners.remove(key);
2637     }
2638 
2639     private void invokeConfigurationListeners() {
2640         Throwable t = null;
2641 
2642         // We're using an IdentityHashMap because we want to compare
2643         // keys using identity (==).
2644         // We don't want to loop within a block synchronized on 'listeners'
2645         // to avoid invoking listeners from yet another synchronized block.
2646         // So we're taking a snapshot of the values list to avoid the risk of
2647         // ConcurrentModificationException while looping.
2648         //
2649         for (Runnable c : listeners.values().toArray(new Runnable[0])) {
2650             try {
2651                 c.run();
2652             } catch (ThreadDeath death) {
2653                 throw death;
2654             } catch (Error | RuntimeException x) {
2655                 if (t == null) t = x;
2656                 else t.addSuppressed(x);
2657             }
2658         }
2659         // Listeners are not supposed to throw exceptions, but if that
2660         // happens, we will rethrow the first error or exception that is raised
2661         // after all listeners have been invoked.
2662         if (t instanceof Error) throw (Error)t;
2663         if (t instanceof RuntimeException) throw (RuntimeException)t;
2664     }
2665 
2666     /**
2667      * This class allows the {@link LoggingProviderImpl} to demand loggers on
2668      * behalf of system and application classes.
2669      */
2670     private static final class LoggingProviderAccess
2671         implements LoggingProviderImpl.LogManagerAccess,
2672                    PrivilegedAction<Void> {
2673 
2674         private LoggingProviderAccess() {
2675         }
2676 
2677         /**
2678          * Demands a logger on behalf of the given {@code module}.
2679          * <p>
2680          * If a named logger suitable for the given module is found
2681          * returns it.
2682          * Otherwise, creates a new logger suitable for the given module.
2683          *
2684          * @param name   The logger name.
2685          * @param module The module on which behalf the logger is created/retrieved.
2686          * @return A logger for the given {@code module}.
2687          *
2688          * @throws NullPointerException if {@code name} is {@code null}
2689          *         or {@code module} is {@code null}.
2690          * @throws IllegalArgumentException if {@code manager} is not the default
2691          *         LogManager.
2692          * @throws SecurityException if a security manager is present and the
2693          *         calling code doesn't have the
2694          *        {@link LoggingPermission LoggingPermission("demandLogger", null)}.
2695          */
2696         @Override
2697         public Logger demandLoggerFor(LogManager manager, String name, Module module) {
2698             if (manager != getLogManager()) {
2699                 // having LogManager as parameter just ensures that the
2700                 // caller will have initialized the LogManager before reaching
2701                 // here.
2702                 throw new IllegalArgumentException("manager");
2703             }
2704             Objects.requireNonNull(name);
2705             Objects.requireNonNull(module);
2706             SecurityManager sm = System.getSecurityManager();
2707             if (sm != null) {
2708                 sm.checkPermission(controlPermission);
2709             }
2710             if (isSystem(module)) {
2711                 return manager.demandSystemLogger(name,
2712                     Logger.SYSTEM_LOGGER_RB_NAME, module);
2713             } else {
2714                 return manager.demandLogger(name, null, module);
2715             }
2716         }
2717 
2718         @Override
2719         public Void run() {
2720             LoggingProviderImpl.setLogManagerAccess(INSTANCE);
2721             return null;
2722         }
2723 
2724         static final LoggingProviderAccess INSTANCE = new LoggingProviderAccess();
2725     }
2726 
2727     static {
2728         AccessController.doPrivileged(LoggingProviderAccess.INSTANCE, null,
2729                                       controlPermission);
2730     }
2731 
2732 }