1 /*
   2  * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 
  27 package java.util.logging;
  28 
  29 import java.io.*;
  30 import java.util.*;
  31 import java.security.*;
  32 import java.lang.ref.ReferenceQueue;
  33 import java.lang.ref.WeakReference;
  34 import java.util.concurrent.ConcurrentHashMap;
  35 import java.util.concurrent.CopyOnWriteArrayList;
  36 import java.util.concurrent.locks.ReentrantLock;
  37 import jdk.internal.misc.JavaAWTAccess;
  38 import jdk.internal.misc.SharedSecrets;
  39 import sun.misc.ManagedLocalsThread;
  40 
  41 /**
  42  * There is a single global LogManager object that is used to
  43  * maintain a set of shared state about Loggers and log services.
  44  * <p>
  45  * This LogManager object:
  46  * <ul>
  47  * <li> Manages a hierarchical namespace of Logger objects.  All
  48  *      named Loggers are stored in this namespace.
  49  * <li> Manages a set of logging control properties.  These are
  50  *      simple key-value pairs that can be used by Handlers and
  51  *      other logging objects to configure themselves.
  52  * </ul>
  53  * <p>
  54  * The global LogManager object can be retrieved using LogManager.getLogManager().
  55  * The LogManager object is created during class initialization and
  56  * cannot subsequently be changed.
  57  * <p>
  58  * At startup the LogManager class is located using the
  59  * java.util.logging.manager system property.
  60  * <p>
  61  * The LogManager defines two optional system properties that allow control over
  62  * the initial configuration:
  63  * <ul>
  64  * <li>"java.util.logging.config.class"
  65  * <li>"java.util.logging.config.file"
  66  * </ul>
  67  * These two properties may be specified on the command line to the "java"
  68  * command, or as system property definitions passed to JNI_CreateJavaVM.
  69  * <p>
  70  * If the "java.util.logging.config.class" property is set, then the
  71  * property value is treated as a class name.  The given class will be
  72  * loaded, an object will be instantiated, and that object's constructor
  73  * is responsible for reading in the initial configuration.  (That object
  74  * may use other system properties to control its configuration.)  The
  75  * alternate configuration class can use {@code readConfiguration(InputStream)}
  76  * to define properties in the LogManager.
  77  * <p>
  78  * If "java.util.logging.config.class" property is <b>not</b> set,
  79  * then the "java.util.logging.config.file" system property can be used
  80  * to specify a properties file (in java.util.Properties format). The
  81  * initial logging configuration will be read from this file.
  82  * <p>
  83  * If neither of these properties is defined then the LogManager uses its
  84  * default configuration. The default configuration is typically loaded from the
  85  * properties file "{@code conf/logging.properties}" in the Java installation
  86  * directory.
  87  * <p>
  88  * The properties for loggers and Handlers will have names starting
  89  * with the dot-separated name for the handler or logger.
  90  * <p>
  91  * The global logging properties may include:
  92  * <ul>
  93  * <li>A property "handlers".  This defines a whitespace or comma separated
  94  * list of class names for handler classes to load and register as
  95  * handlers on the root Logger (the Logger named "").  Each class
  96  * name must be for a Handler class which has a default constructor.
  97  * Note that these Handlers may be created lazily, when they are
  98  * first used.
  99  *
 100  * <li>A property "&lt;logger&gt;.handlers". This defines a whitespace or
 101  * comma separated list of class names for handlers classes to
 102  * load and register as handlers to the specified logger. Each class
 103  * name must be for a Handler class which has a default constructor.
 104  * Note that these Handlers may be created lazily, when they are
 105  * first used.
 106  *
 107  * <li>A property "&lt;logger&gt;.handlers.ensureCloseOnReset". This defines a
 108  * a boolean value. If "&lt;logger&gt;.handlers" is not defined or is empty,
 109  * this property is ignored. Otherwise it defaults to {@code true}. When the
 110  * value is {@code true}, the handlers associated with the logger are guaranteed
 111  * to be closed on {@linkplain #reset} and shutdown. This can be turned off
 112  * by explicitly setting "&lt;logger&gt;.handlers.ensureCloseOnReset=false" in
 113  * the configuration. Note that turning this property off causes the risk of
 114  * introducing a resource leak, as the logger may get garbage collected before
 115  * {@code reset()} is called, thus preventing its handlers from being closed
 116  * on {@code reset()}. In that case it is the responsibility of the application
 117  * to ensure that the handlers are closed before the logger is garbage
 118  * collected.
 119  *
 120  * <li>A property "&lt;logger&gt;.useParentHandlers". This defines a boolean
 121  * value. By default every logger calls its parent in addition to
 122  * handling the logging message itself, this often result in messages
 123  * being handled by the root logger as well. When setting this property
 124  * to false a Handler needs to be configured for this logger otherwise
 125  * no logging messages are delivered.
 126  *
 127  * <li>A property "config".  This property is intended to allow
 128  * arbitrary configuration code to be run.  The property defines a
 129  * whitespace or comma separated list of class names.  A new instance will be
 130  * created for each named class.  The default constructor of each class
 131  * may execute arbitrary code to update the logging configuration, such as
 132  * setting logger levels, adding handlers, adding filters, etc.
 133  * </ul>
 134  * <p>
 135  * Note that all classes loaded during LogManager configuration are
 136  * first searched on the system class path before any user class path.
 137  * That includes the LogManager class, any config classes, and any
 138  * handler classes.
 139  * <p>
 140  * Loggers are organized into a naming hierarchy based on their
 141  * dot separated names.  Thus "a.b.c" is a child of "a.b", but
 142  * "a.b1" and a.b2" are peers.
 143  * <p>
 144  * All properties whose names end with ".level" are assumed to define
 145  * log levels for Loggers.  Thus "foo.level" defines a log level for
 146  * the logger called "foo" and (recursively) for any of its children
 147  * in the naming hierarchy.  Log Levels are applied in the order they
 148  * are defined in the properties file.  Thus level settings for child
 149  * nodes in the tree should come after settings for their parents.
 150  * The property name ".level" can be used to set the level for the
 151  * root of the tree.
 152  * <p>
 153  * All methods on the LogManager object are multi-thread safe.
 154  *
 155  * @since 1.4
 156 */
 157 
 158 public class LogManager {
 159     // The global LogManager object
 160     private static final LogManager manager;
 161 
 162     // 'props' is assigned within a lock but accessed without it.
 163     // Declaring it volatile makes sure that another thread will not
 164     // be able to see a partially constructed 'props' object.
 165     // (seeing a partially constructed 'props' object can result in
 166     // NPE being thrown in Hashtable.get(), because it leaves the door
 167     // open for props.getProperties() to be called before the construcor
 168     // of Hashtable is actually completed).
 169     private volatile Properties props = new Properties();
 170     private final static Level defaultLevel = Level.INFO;
 171 
 172     // LoggerContext for system loggers and user loggers
 173     private final LoggerContext systemContext = new SystemLoggerContext();
 174     private final LoggerContext userContext = new LoggerContext();
 175     // non final field - make it volatile to make sure that other threads
 176     // will see the new value once ensureLogManagerInitialized() has finished
 177     // executing.
 178     private volatile Logger rootLogger;
 179     // Have we done the primordial reading of the configuration file?
 180     // (Must be done after a suitable amount of java.lang.System
 181     // initialization has been done)
 182     private volatile boolean readPrimordialConfiguration;
 183     // Have we initialized global (root) handlers yet?
 184     // This gets set to STATE_UNINITIALIZED in readConfiguration
 185     private static final int
 186             STATE_INITIALIZED = 0, // initial state
 187             STATE_INITIALIZING = 1,
 188             STATE_READING_CONFIG = 2,
 189             STATE_UNINITIALIZED = 3,
 190             STATE_SHUTDOWN = 4;    // terminal state
 191     private volatile int globalHandlersState; // = STATE_INITIALIZED;
 192     // A concurrency lock for reset(), readConfiguration() and Cleaner.
 193     private final ReentrantLock configurationLock = new ReentrantLock();
 194 
 195     // This list contains the loggers for which some handlers have been
 196     // explicitly configured in the configuration file.
 197     // It prevents these loggers from being arbitrarily garbage collected.
 198     private static final class CloseOnReset {
 199         private final Logger logger;
 200         private CloseOnReset(Logger ref) {
 201             this.logger = Objects.requireNonNull(ref);
 202         }
 203         @Override
 204         public boolean equals(Object other) {
 205             return (other instanceof CloseOnReset) && ((CloseOnReset)other).logger == logger;
 206         }
 207         @Override
 208         public int hashCode() {
 209             return System.identityHashCode(logger);
 210         }
 211         public Logger get() {
 212             return logger;
 213         }
 214         public static CloseOnReset create(Logger logger) {
 215             return new CloseOnReset(logger);
 216         }
 217     }
 218     private final CopyOnWriteArrayList<CloseOnReset> closeOnResetLoggers =
 219             new CopyOnWriteArrayList<>();
 220 
 221 
 222     private final Map<Object, Runnable> listeners =
 223             Collections.synchronizedMap(new IdentityHashMap<>());
 224 
 225     static {
 226         manager = AccessController.doPrivileged(new PrivilegedAction<LogManager>() {
 227             @Override
 228             public LogManager run() {
 229                 LogManager mgr = null;
 230                 String cname = null;
 231                 try {
 232                     cname = System.getProperty("java.util.logging.manager");
 233                     if (cname != null) {
 234                         try {
 235                             Class<?> clz = ClassLoader.getSystemClassLoader()
 236                                     .loadClass(cname);
 237                             mgr = (LogManager) clz.newInstance();
 238                         } catch (ClassNotFoundException ex) {
 239                             Class<?> clz = Thread.currentThread()
 240                                     .getContextClassLoader().loadClass(cname);
 241                             mgr = (LogManager) clz.newInstance();
 242                         }
 243                     }
 244                 } catch (Exception ex) {
 245                     System.err.println("Could not load Logmanager \"" + cname + "\"");
 246                     ex.printStackTrace();
 247                 }
 248                 if (mgr == null) {
 249                     mgr = new LogManager();
 250                 }
 251                 return mgr;
 252 
 253             }
 254         });
 255     }
 256 
 257     // This private class is used as a shutdown hook.
 258     // It does a "reset" to close all open handlers.
 259     private class Cleaner extends ManagedLocalsThread {
 260 
 261         private Cleaner() {
 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                         // Read configuration.
 389                         owner.readPrimordialConfiguration();
 390 
 391                         // Create and retain Logger for the root of the namespace.
 392                         owner.rootLogger = owner.new RootLogger();
 393                         owner.addLogger(owner.rootLogger);
 394                         if (!owner.rootLogger.isLevelInitialized()) {
 395                             owner.rootLogger.setLevel(defaultLevel);
 396                         }
 397 
 398                         // Adding the global Logger.
 399                         // Do not call Logger.getGlobal() here as this might trigger
 400                         // subtle inter-dependency issues.
 401                         @SuppressWarnings("deprecation")
 402                         final Logger global = Logger.global;
 403 
 404                         // Make sure the global logger will be registered in the
 405                         // global manager
 406                         owner.addLogger(global);
 407                         return null;
 408                     }
 409                 });
 410             } finally {
 411                 initializationDone = true;
 412             }
 413         } finally {
 414             configurationLock.unlock();
 415         }
 416     }
 417 
 418     /**
 419      * Returns the global LogManager object.
 420      * @return the global LogManager object
 421      */
 422     public static LogManager getLogManager() {
 423         if (manager != null) {
 424             manager.ensureLogManagerInitialized();
 425         }
 426         return manager;
 427     }
 428 
 429     private void readPrimordialConfiguration() { // must be called while holding configurationLock
 430         if (!readPrimordialConfiguration) {
 431             // If System.in/out/err are null, it's a good
 432             // indication that we're still in the
 433             // bootstrapping phase
 434             if (System.out == null) {
 435                 return;
 436             }
 437             readPrimordialConfiguration = true;
 438             try {
 439                 readConfiguration();
 440 
 441                 // Platform loggers begin to delegate to java.util.logging.Logger
 442                 sun.util.logger.BootstrapLogger.redirectTemporaryLoggers();
 443 
 444             } catch (Exception ex) {
 445                 assert false : "Exception raised while reading logging configuration: " + ex;
 446             }
 447         }
 448     }
 449 
 450     // LoggerContext maps from AppContext
 451     private WeakHashMap<Object, LoggerContext> contextsMap = null;
 452 
 453     // Returns the LoggerContext for the user code (i.e. application or AppContext).
 454     // Loggers are isolated from each AppContext.
 455     private LoggerContext getUserContext() {
 456         LoggerContext context = null;
 457 
 458         SecurityManager sm = System.getSecurityManager();
 459         JavaAWTAccess javaAwtAccess = SharedSecrets.getJavaAWTAccess();
 460         if (sm != null && javaAwtAccess != null) {
 461             // for each applet, it has its own LoggerContext isolated from others
 462             final Object ecx = javaAwtAccess.getAppletContext();
 463             if (ecx != null) {
 464                 synchronized (javaAwtAccess) {
 465                     // find the AppContext of the applet code
 466                     // will be null if we are in the main app context.
 467                     if (contextsMap == null) {
 468                         contextsMap = new WeakHashMap<>();
 469                     }
 470                     context = contextsMap.get(ecx);
 471                     if (context == null) {
 472                         // Create a new LoggerContext for the applet.
 473                         context = new LoggerContext();
 474                         contextsMap.put(ecx, context);
 475                     }
 476                 }
 477             }
 478         }
 479         // for standalone app, return userContext
 480         return context != null ? context : userContext;
 481     }
 482 
 483     // The system context.
 484     final LoggerContext getSystemContext() {
 485         return systemContext;
 486     }
 487 
 488     private List<LoggerContext> contexts() {
 489         List<LoggerContext> cxs = new ArrayList<>();
 490         cxs.add(getSystemContext());
 491         cxs.add(getUserContext());
 492         return cxs;
 493     }
 494 
 495     // Find or create a specified logger instance. If a logger has
 496     // already been created with the given name it is returned.
 497     // Otherwise a new logger instance is created and registered
 498     // in the LogManager global namespace.
 499     // This method will always return a non-null Logger object.
 500     // Synchronization is not required here. All synchronization for
 501     // adding a new Logger object is handled by addLogger().
 502     //
 503     // This method must delegate to the LogManager implementation to
 504     // add a new Logger or return the one that has been added previously
 505     // as a LogManager subclass may override the addLogger, getLogger,
 506     // readConfiguration, and other methods.
 507     Logger demandLogger(String name, String resourceBundleName, Class<?> caller) {
 508         Logger result = getLogger(name);
 509         if (result == null) {
 510             // only allocate the new logger once
 511             Logger newLogger = new Logger(name, resourceBundleName, caller, this, false);
 512             do {
 513                 if (addLogger(newLogger)) {
 514                     // We successfully added the new Logger that we
 515                     // created above so return it without refetching.
 516                     return newLogger;
 517                 }
 518 
 519                 // We didn't add the new Logger that we created above
 520                 // because another thread added a Logger with the same
 521                 // name after our null check above and before our call
 522                 // to addLogger(). We have to refetch the Logger because
 523                 // addLogger() returns a boolean instead of the Logger
 524                 // reference itself. However, if the thread that created
 525                 // the other Logger is not holding a strong reference to
 526                 // the other Logger, then it is possible for the other
 527                 // Logger to be GC'ed after we saw it in addLogger() and
 528                 // before we can refetch it. If it has been GC'ed then
 529                 // we'll just loop around and try again.
 530                 result = getLogger(name);
 531             } while (result == null);
 532         }
 533         return result;
 534     }
 535 
 536     Logger demandSystemLogger(String name, String resourceBundleName, Class<?> caller) {
 537         // Add a system logger in the system context's namespace
 538         final Logger sysLogger = getSystemContext()
 539                 .demandLogger(name, resourceBundleName, caller);
 540 
 541         // Add the system logger to the LogManager's namespace if not exist
 542         // so that there is only one single logger of the given name.
 543         // System loggers are visible to applications unless a logger of
 544         // the same name has been added.
 545         Logger logger;
 546         do {
 547             // First attempt to call addLogger instead of getLogger
 548             // This would avoid potential bug in custom LogManager.getLogger
 549             // implementation that adds a logger if does not exist
 550             if (addLogger(sysLogger)) {
 551                 // successfully added the new system logger
 552                 logger = sysLogger;
 553             } else {
 554                 logger = getLogger(name);
 555             }
 556         } while (logger == null);
 557 
 558         // LogManager will set the sysLogger's handlers via LogManager.addLogger method.
 559         if (logger != sysLogger && sysLogger.accessCheckedHandlers().length == 0) {
 560             // if logger already exists but handlers not set
 561             final Logger l = logger;
 562             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 563                 @Override
 564                 public Void run() {
 565                     for (Handler hdl : l.accessCheckedHandlers()) {
 566                         sysLogger.addHandler(hdl);
 567                     }
 568                     return null;
 569                 }
 570             });
 571         }
 572         return sysLogger;
 573     }
 574 
 575     // LoggerContext maintains the logger namespace per context.
 576     // The default LogManager implementation has one system context and user
 577     // context.  The system context is used to maintain the namespace for
 578     // all system loggers and is queried by the system code.  If a system logger
 579     // doesn't exist in the user context, it'll also be added to the user context.
 580     // The user context is queried by the user code and all other loggers are
 581     // added in the user context.
 582     class LoggerContext {
 583         // Table of named Loggers that maps names to Loggers.
 584         private final ConcurrentHashMap<String,LoggerWeakRef> namedLoggers =
 585                 new ConcurrentHashMap<>();
 586         // Tree of named Loggers
 587         private final LogNode root;
 588         private LoggerContext() {
 589             this.root = new LogNode(null, this);
 590         }
 591 
 592 
 593         // Tells whether default loggers are required in this context.
 594         // If true, the default loggers will be lazily added.
 595         final boolean requiresDefaultLoggers() {
 596             final boolean requiresDefaultLoggers = (getOwner() == manager);
 597             if (requiresDefaultLoggers) {
 598                 getOwner().ensureLogManagerInitialized();
 599             }
 600             return requiresDefaultLoggers;
 601         }
 602 
 603         // This context's LogManager.
 604         final LogManager getOwner() {
 605             return LogManager.this;
 606         }
 607 
 608         // This context owner's root logger, which if not null, and if
 609         // the context requires default loggers, will be added to the context
 610         // logger's tree.
 611         final Logger getRootLogger() {
 612             return getOwner().rootLogger;
 613         }
 614 
 615         // The global logger, which if not null, and if
 616         // the context requires default loggers, will be added to the context
 617         // logger's tree.
 618         final Logger getGlobalLogger() {
 619             @SuppressWarnings("deprecation") // avoids initialization cycles.
 620             final Logger global = Logger.global;
 621             return global;
 622         }
 623 
 624         Logger demandLogger(String name, String resourceBundleName, Class<?> caller) {
 625             // a LogManager subclass may have its own implementation to add and
 626             // get a Logger.  So delegate to the LogManager to do the work.
 627             final LogManager owner = getOwner();
 628             return owner.demandLogger(name, resourceBundleName, caller);
 629         }
 630 
 631 
 632         // Due to subtle deadlock issues getUserContext() no longer
 633         // calls addLocalLogger(rootLogger);
 634         // Therefore - we need to add the default loggers later on.
 635         // Checks that the context is properly initialized
 636         // This is necessary before calling e.g. find(name)
 637         // or getLoggerNames()
 638         //
 639         private void ensureInitialized() {
 640             if (requiresDefaultLoggers()) {
 641                 // Ensure that the root and global loggers are set.
 642                 ensureDefaultLogger(getRootLogger());
 643                 ensureDefaultLogger(getGlobalLogger());
 644             }
 645         }
 646 
 647 
 648         Logger findLogger(String name) {
 649             // Attempt to find logger without locking.
 650             LoggerWeakRef ref = namedLoggers.get(name);
 651             Logger logger = ref == null ? null : ref.get();
 652 
 653             // if logger is not null, then we can return it right away.
 654             // if name is "" or "global" and logger is null
 655             // we need to fall through and check that this context is
 656             // initialized.
 657             // if ref is not null and logger is null we also need to
 658             // fall through.
 659             if (logger != null || (ref == null && !name.isEmpty()
 660                     && !name.equals(Logger.GLOBAL_LOGGER_NAME))) {
 661                 return logger;
 662             }
 663 
 664             // We either found a stale reference, or we were looking for
 665             // "" or "global" and didn't find them.
 666             // Make sure context is initialized (has the default loggers),
 667             // and look up again, cleaning the stale reference if it hasn't
 668             // been cleaned up in between. All this needs to be done inside
 669             // a synchronized block.
 670             synchronized(this) {
 671                 // ensure that this context is properly initialized before
 672                 // looking for loggers.
 673                 ensureInitialized();
 674                 ref = namedLoggers.get(name);
 675                 if (ref == null) {
 676                     return null;
 677                 }
 678                 logger = ref.get();
 679                 if (logger == null) {
 680                     // The namedLoggers map holds stale weak reference
 681                     // to a logger which has been GC-ed.
 682                     ref.dispose();
 683                 }
 684                 return logger;
 685             }
 686         }
 687 
 688         // This method is called before adding a logger to the
 689         // context.
 690         // 'logger' is the context that will be added.
 691         // This method will ensure that the defaults loggers are added
 692         // before adding 'logger'.
 693         //
 694         private void ensureAllDefaultLoggers(Logger logger) {
 695             if (requiresDefaultLoggers()) {
 696                 final String name = logger.getName();
 697                 if (!name.isEmpty()) {
 698                     ensureDefaultLogger(getRootLogger());
 699                     if (!Logger.GLOBAL_LOGGER_NAME.equals(name)) {
 700                         ensureDefaultLogger(getGlobalLogger());
 701                     }
 702                 }
 703             }
 704         }
 705 
 706         private void ensureDefaultLogger(Logger logger) {
 707             // Used for lazy addition of root logger and global logger
 708             // to a LoggerContext.
 709 
 710             // This check is simple sanity: we do not want that this
 711             // method be called for anything else than Logger.global
 712             // or owner.rootLogger.
 713             if (!requiresDefaultLoggers() || logger == null
 714                     || logger != getGlobalLogger() && logger != LogManager.this.rootLogger ) {
 715 
 716                 // the case where we have a non null logger which is neither
 717                 // Logger.global nor manager.rootLogger indicates a serious
 718                 // issue - as ensureDefaultLogger should never be called
 719                 // with any other loggers than one of these two (or null - if
 720                 // e.g manager.rootLogger is not yet initialized)...
 721                 assert logger == null;
 722 
 723                 return;
 724             }
 725 
 726             // Adds the logger if it's not already there.
 727             if (!namedLoggers.containsKey(logger.getName())) {
 728                 // It is important to prevent addLocalLogger to
 729                 // call ensureAllDefaultLoggers when we're in the process
 730                 // off adding one of those default loggers - as this would
 731                 // immediately cause a stack overflow.
 732                 // Therefore we must pass addDefaultLoggersIfNeeded=false,
 733                 // even if requiresDefaultLoggers is true.
 734                 addLocalLogger(logger, false);
 735             }
 736         }
 737 
 738         boolean addLocalLogger(Logger logger) {
 739             // no need to add default loggers if it's not required
 740             return addLocalLogger(logger, requiresDefaultLoggers());
 741         }
 742 
 743         // Add a logger to this context.  This method will only set its level
 744         // and process parent loggers.  It doesn't set its handlers.
 745         synchronized boolean addLocalLogger(Logger logger, boolean addDefaultLoggersIfNeeded) {
 746             // addDefaultLoggersIfNeeded serves to break recursion when adding
 747             // default loggers. If we're adding one of the default loggers
 748             // (we're being called from ensureDefaultLogger()) then
 749             // addDefaultLoggersIfNeeded will be false: we don't want to
 750             // call ensureAllDefaultLoggers again.
 751             //
 752             // Note: addDefaultLoggersIfNeeded can also be false when
 753             //       requiresDefaultLoggers is false - since calling
 754             //       ensureAllDefaultLoggers would have no effect in this case.
 755             if (addDefaultLoggersIfNeeded) {
 756                 ensureAllDefaultLoggers(logger);
 757             }
 758 
 759             final String name = logger.getName();
 760             if (name == null) {
 761                 throw new NullPointerException();
 762             }
 763             LoggerWeakRef ref = namedLoggers.get(name);
 764             if (ref != null) {
 765                 if (ref.get() == null) {
 766                     // It's possible that the Logger was GC'ed after a
 767                     // drainLoggerRefQueueBounded() call above so allow
 768                     // a new one to be registered.
 769                     ref.dispose();
 770                 } else {
 771                     // We already have a registered logger with the given name.
 772                     return false;
 773                 }
 774             }
 775 
 776             // We're adding a new logger.
 777             // Note that we are creating a weak reference here.
 778             final LogManager owner = getOwner();
 779             logger.setLogManager(owner);
 780             ref = owner.new LoggerWeakRef(logger);
 781 
 782             // Apply any initial level defined for the new logger, unless
 783             // the logger's level is already initialized
 784             Level level = owner.getLevelProperty(name + ".level", null);
 785             if (level != null && !logger.isLevelInitialized()) {
 786                 doSetLevel(logger, level);
 787             }
 788 
 789             // instantiation of the handler is done in the LogManager.addLogger
 790             // implementation as a handler class may be only visible to LogManager
 791             // subclass for the custom log manager case
 792             processParentHandlers(logger, name);
 793 
 794             // Find the new node and its parent.
 795             LogNode node = getNode(name);
 796             node.loggerRef = ref;
 797             Logger parent = null;
 798             LogNode nodep = node.parent;
 799             while (nodep != null) {
 800                 LoggerWeakRef nodeRef = nodep.loggerRef;
 801                 if (nodeRef != null) {
 802                     parent = nodeRef.get();
 803                     if (parent != null) {
 804                         break;
 805                     }
 806                 }
 807                 nodep = nodep.parent;
 808             }
 809 
 810             if (parent != null) {
 811                 doSetParent(logger, parent);
 812             }
 813             // Walk over the children and tell them we are their new parent.
 814             node.walkAndSetParent(logger);
 815             // new LogNode is ready so tell the LoggerWeakRef about it
 816             ref.setNode(node);
 817 
 818             // Do not publish 'ref' in namedLoggers before the logger tree
 819             // is fully updated - because the named logger will be visible as
 820             // soon as it is published in namedLoggers (findLogger takes
 821             // benefit of the ConcurrentHashMap implementation of namedLoggers
 822             // to avoid synchronizing on retrieval when that is possible).
 823             namedLoggers.put(name, ref);
 824             return true;
 825         }
 826 
 827         void removeLoggerRef(String name, LoggerWeakRef ref) {
 828             namedLoggers.remove(name, ref);
 829         }
 830 
 831         synchronized Enumeration<String> getLoggerNames() {
 832             // ensure that this context is properly initialized before
 833             // returning logger names.
 834             ensureInitialized();
 835             return Collections.enumeration(namedLoggers.keySet());
 836         }
 837 
 838         // If logger.getUseParentHandlers() returns 'true' and any of the logger's
 839         // parents have levels or handlers defined, make sure they are instantiated.
 840         private void processParentHandlers(final Logger logger, final String name) {
 841             final LogManager owner = getOwner();
 842             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 843                 @Override
 844                 public Void run() {
 845                     if (logger != owner.rootLogger) {
 846                         boolean useParent = owner.getBooleanProperty(name + ".useParentHandlers", true);
 847                         if (!useParent) {
 848                             logger.setUseParentHandlers(false);
 849                         }
 850                     }
 851                     return null;
 852                 }
 853             });
 854 
 855             int ix = 1;
 856             for (;;) {
 857                 int ix2 = name.indexOf('.', ix);
 858                 if (ix2 < 0) {
 859                     break;
 860                 }
 861                 String pname = name.substring(0, ix2);
 862                 if (owner.getProperty(pname + ".level") != null ||
 863                     owner.getProperty(pname + ".handlers") != null) {
 864                     // This pname has a level/handlers definition.
 865                     // Make sure it exists.
 866                     demandLogger(pname, null, null);
 867                 }
 868                 ix = ix2+1;
 869             }
 870         }
 871 
 872         // Gets a node in our tree of logger nodes.
 873         // If necessary, create it.
 874         LogNode getNode(String name) {
 875             if (name == null || name.equals("")) {
 876                 return root;
 877             }
 878             LogNode node = root;
 879             while (name.length() > 0) {
 880                 int ix = name.indexOf('.');
 881                 String head;
 882                 if (ix > 0) {
 883                     head = name.substring(0, ix);
 884                     name = name.substring(ix + 1);
 885                 } else {
 886                     head = name;
 887                     name = "";
 888                 }
 889                 if (node.children == null) {
 890                     node.children = new HashMap<>();
 891                 }
 892                 LogNode child = node.children.get(head);
 893                 if (child == null) {
 894                     child = new LogNode(node, this);
 895                     node.children.put(head, child);
 896                 }
 897                 node = child;
 898             }
 899             return node;
 900         }
 901     }
 902 
 903     final class SystemLoggerContext extends LoggerContext {
 904         // Add a system logger in the system context's namespace as well as
 905         // in the LogManager's namespace if not exist so that there is only
 906         // one single logger of the given name.  System loggers are visible
 907         // to applications unless a logger of the same name has been added.
 908         @Override
 909         Logger demandLogger(String name, String resourceBundleName, Class<?> caller) {
 910             Logger result = findLogger(name);
 911             if (result == null) {
 912                 // only allocate the new system logger once
 913                 Logger newLogger = new Logger(name, resourceBundleName, caller, getOwner(), true);
 914                 do {
 915                     if (addLocalLogger(newLogger)) {
 916                         // We successfully added the new Logger that we
 917                         // created above so return it without refetching.
 918                         result = newLogger;
 919                     } else {
 920                         // We didn't add the new Logger that we created above
 921                         // because another thread added a Logger with the same
 922                         // name after our null check above and before our call
 923                         // to addLogger(). We have to refetch the Logger because
 924                         // addLogger() returns a boolean instead of the Logger
 925                         // reference itself. However, if the thread that created
 926                         // the other Logger is not holding a strong reference to
 927                         // the other Logger, then it is possible for the other
 928                         // Logger to be GC'ed after we saw it in addLogger() and
 929                         // before we can refetch it. If it has been GC'ed then
 930                         // we'll just loop around and try again.
 931                         result = findLogger(name);
 932                     }
 933                 } while (result == null);
 934             }
 935             return result;
 936         }
 937     }
 938 
 939     // Add new per logger handlers.
 940     // We need to raise privilege here. All our decisions will
 941     // be made based on the logging configuration, which can
 942     // only be modified by trusted code.
 943     private void loadLoggerHandlers(final Logger logger, final String name,
 944                                     final String handlersPropertyName)
 945     {
 946         AccessController.doPrivileged(new PrivilegedAction<Object>() {
 947             @Override
 948             public Object run() {
 949                 String names[] = parseClassNames(handlersPropertyName);
 950                 final boolean ensureCloseOnReset = names.length > 0
 951                     && getBooleanProperty(handlersPropertyName + ".ensureCloseOnReset",true);
 952 
 953                 int count = 0;
 954                 for (String type : names) {
 955                     try {
 956                         Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(type);
 957                         Handler hdl = (Handler) clz.newInstance();
 958                         // Check if there is a property defining the
 959                         // this handler's level.
 960                         String levs = getProperty(type + ".level");
 961                         if (levs != null) {
 962                             Level l = Level.findLevel(levs);
 963                             if (l != null) {
 964                                 hdl.setLevel(l);
 965                             } else {
 966                                 // Probably a bad level. Drop through.
 967                                 System.err.println("Can't set level for " + type);
 968                             }
 969                         }
 970                         // Add this Handler to the logger
 971                         logger.addHandler(hdl);
 972                         if (++count == 1 && ensureCloseOnReset) {
 973                             // add this logger to the closeOnResetLoggers list.
 974                             closeOnResetLoggers.addIfAbsent(CloseOnReset.create(logger));
 975                         }
 976                     } catch (Exception ex) {
 977                         System.err.println("Can't load log handler \"" + type + "\"");
 978                         System.err.println("" + ex);
 979                         ex.printStackTrace();
 980                     }
 981                 }
 982 
 983                 return null;
 984             }
 985         });
 986     }
 987 
 988 
 989     // loggerRefQueue holds LoggerWeakRef objects for Logger objects
 990     // that have been GC'ed.
 991     private final ReferenceQueue<Logger> loggerRefQueue
 992         = new ReferenceQueue<>();
 993 
 994     // Package-level inner class.
 995     // Helper class for managing WeakReferences to Logger objects.
 996     //
 997     // LogManager.namedLoggers
 998     //     - has weak references to all named Loggers
 999     //     - namedLoggers keeps the LoggerWeakRef objects for the named
1000     //       Loggers around until we can deal with the book keeping for
1001     //       the named Logger that is being GC'ed.
1002     // LogManager.LogNode.loggerRef
1003     //     - has a weak reference to a named Logger
1004     //     - the LogNode will also keep the LoggerWeakRef objects for
1005     //       the named Loggers around; currently LogNodes never go away.
1006     // Logger.kids
1007     //     - has a weak reference to each direct child Logger; this
1008     //       includes anonymous and named Loggers
1009     //     - anonymous Loggers are always children of the rootLogger
1010     //       which is a strong reference; rootLogger.kids keeps the
1011     //       LoggerWeakRef objects for the anonymous Loggers around
1012     //       until we can deal with the book keeping.
1013     //
1014     final class LoggerWeakRef extends WeakReference<Logger> {
1015         private String                name;       // for namedLoggers cleanup
1016         private LogNode               node;       // for loggerRef cleanup
1017         private WeakReference<Logger> parentRef;  // for kids cleanup
1018         private boolean disposed = false;         // avoid calling dispose twice
1019 
1020         LoggerWeakRef(Logger logger) {
1021             super(logger, loggerRefQueue);
1022 
1023             name = logger.getName();  // save for namedLoggers cleanup
1024         }
1025 
1026         // dispose of this LoggerWeakRef object
1027         void dispose() {
1028             // Avoid calling dispose twice. When a Logger is gc'ed, its
1029             // LoggerWeakRef will be enqueued.
1030             // However, a new logger of the same name may be added (or looked
1031             // up) before the queue is drained. When that happens, dispose()
1032             // will be called by addLocalLogger() or findLogger().
1033             // Later when the queue is drained, dispose() will be called again
1034             // for the same LoggerWeakRef. Marking LoggerWeakRef as disposed
1035             // avoids processing the data twice (even though the code should
1036             // now be reentrant).
1037             synchronized(this) {
1038                 // Note to maintainers:
1039                 // Be careful not to call any method that tries to acquire
1040                 // another lock from within this block - as this would surely
1041                 // lead to deadlocks, given that dispose() can be called by
1042                 // multiple threads, and from within different synchronized
1043                 // methods/blocks.
1044                 if (disposed) return;
1045                 disposed = true;
1046             }
1047 
1048             final LogNode n = node;
1049             if (n != null) {
1050                 // n.loggerRef can only be safely modified from within
1051                 // a lock on LoggerContext. removeLoggerRef is already
1052                 // synchronized on LoggerContext so calling
1053                 // n.context.removeLoggerRef from within this lock is safe.
1054                 synchronized (n.context) {
1055                     // if we have a LogNode, then we were a named Logger
1056                     // so clear namedLoggers weak ref to us
1057                     n.context.removeLoggerRef(name, this);
1058                     name = null;  // clear our ref to the Logger's name
1059 
1060                     // LogNode may have been reused - so only clear
1061                     // LogNode.loggerRef if LogNode.loggerRef == this
1062                     if (n.loggerRef == this) {
1063                         n.loggerRef = null;  // clear LogNode's weak ref to us
1064                     }
1065                     node = null;            // clear our ref to LogNode
1066                 }
1067             }
1068 
1069             if (parentRef != null) {
1070                 // this LoggerWeakRef has or had a parent Logger
1071                 Logger parent = parentRef.get();
1072                 if (parent != null) {
1073                     // the parent Logger is still there so clear the
1074                     // parent Logger's weak ref to us
1075                     parent.removeChildLogger(this);
1076                 }
1077                 parentRef = null;  // clear our weak ref to the parent Logger
1078             }
1079         }
1080 
1081         // set the node field to the specified value
1082         void setNode(LogNode node) {
1083             this.node = node;
1084         }
1085 
1086         // set the parentRef field to the specified value
1087         void setParentRef(WeakReference<Logger> parentRef) {
1088             this.parentRef = parentRef;
1089         }
1090     }
1091 
1092     // Package-level method.
1093     // Drain some Logger objects that have been GC'ed.
1094     //
1095     // drainLoggerRefQueueBounded() is called by addLogger() below
1096     // and by Logger.getAnonymousLogger(String) so we'll drain up to
1097     // MAX_ITERATIONS GC'ed Loggers for every Logger we add.
1098     //
1099     // On a WinXP VMware client, a MAX_ITERATIONS value of 400 gives
1100     // us about a 50/50 mix in increased weak ref counts versus
1101     // decreased weak ref counts in the AnonLoggerWeakRefLeak test.
1102     // Here are stats for cleaning up sets of 400 anonymous Loggers:
1103     //   - test duration 1 minute
1104     //   - sample size of 125 sets of 400
1105     //   - average: 1.99 ms
1106     //   - minimum: 0.57 ms
1107     //   - maximum: 25.3 ms
1108     //
1109     // The same config gives us a better decreased weak ref count
1110     // than increased weak ref count in the LoggerWeakRefLeak test.
1111     // Here are stats for cleaning up sets of 400 named Loggers:
1112     //   - test duration 2 minutes
1113     //   - sample size of 506 sets of 400
1114     //   - average: 0.57 ms
1115     //   - minimum: 0.02 ms
1116     //   - maximum: 10.9 ms
1117     //
1118     private final static int MAX_ITERATIONS = 400;
1119     final void drainLoggerRefQueueBounded() {
1120         for (int i = 0; i < MAX_ITERATIONS; i++) {
1121             if (loggerRefQueue == null) {
1122                 // haven't finished loading LogManager yet
1123                 break;
1124             }
1125 
1126             LoggerWeakRef ref = (LoggerWeakRef) loggerRefQueue.poll();
1127             if (ref == null) {
1128                 break;
1129             }
1130             // a Logger object has been GC'ed so clean it up
1131             ref.dispose();
1132         }
1133     }
1134 
1135     /**
1136      * Add a named logger.  This does nothing and returns false if a logger
1137      * with the same name is already registered.
1138      * <p>
1139      * The Logger factory methods call this method to register each
1140      * newly created Logger.
1141      * <p>
1142      * The application should retain its own reference to the Logger
1143      * object to avoid it being garbage collected.  The LogManager
1144      * may only retain a weak reference.
1145      *
1146      * @param   logger the new logger.
1147      * @return  true if the argument logger was registered successfully,
1148      *          false if a logger of that name already exists.
1149      * @exception NullPointerException if the logger name is null.
1150      */
1151     public boolean addLogger(Logger logger) {
1152         final String name = logger.getName();
1153         if (name == null) {
1154             throw new NullPointerException();
1155         }
1156         drainLoggerRefQueueBounded();
1157         LoggerContext cx = getUserContext();
1158         if (cx.addLocalLogger(logger)) {
1159             // Do we have a per logger handler too?
1160             // Note: this will add a 200ms penalty
1161             loadLoggerHandlers(logger, name, name + ".handlers");
1162             return true;
1163         } else {
1164             return false;
1165         }
1166     }
1167 
1168     // Private method to set a level on a logger.
1169     // If necessary, we raise privilege before doing the call.
1170     private static void doSetLevel(final Logger logger, final Level level) {
1171         SecurityManager sm = System.getSecurityManager();
1172         if (sm == null) {
1173             // There is no security manager, so things are easy.
1174             logger.setLevel(level);
1175             return;
1176         }
1177         // There is a security manager.  Raise privilege before
1178         // calling setLevel.
1179         AccessController.doPrivileged(new PrivilegedAction<Object>() {
1180             @Override
1181             public Object run() {
1182                 logger.setLevel(level);
1183                 return null;
1184             }});
1185     }
1186 
1187     // Private method to set a parent on a logger.
1188     // If necessary, we raise privilege before doing the setParent call.
1189     private static void doSetParent(final Logger logger, final Logger parent) {
1190         SecurityManager sm = System.getSecurityManager();
1191         if (sm == null) {
1192             // There is no security manager, so things are easy.
1193             logger.setParent(parent);
1194             return;
1195         }
1196         // There is a security manager.  Raise privilege before
1197         // calling setParent.
1198         AccessController.doPrivileged(new PrivilegedAction<Object>() {
1199             @Override
1200             public Object run() {
1201                 logger.setParent(parent);
1202                 return null;
1203             }});
1204     }
1205 
1206     /**
1207      * Method to find a named logger.
1208      * <p>
1209      * Note that since untrusted code may create loggers with
1210      * arbitrary names this method should not be relied on to
1211      * find Loggers for security sensitive logging.
1212      * It is also important to note that the Logger associated with the
1213      * String {@code name} may be garbage collected at any time if there
1214      * is no strong reference to the Logger. The caller of this method
1215      * must check the return value for null in order to properly handle
1216      * the case where the Logger has been garbage collected.
1217      *
1218      * @param name name of the logger
1219      * @return  matching logger or null if none is found
1220      */
1221     public Logger getLogger(String name) {
1222         return getUserContext().findLogger(name);
1223     }
1224 
1225     /**
1226      * Get an enumeration of known logger names.
1227      * <p>
1228      * Note:  Loggers may be added dynamically as new classes are loaded.
1229      * This method only reports on the loggers that are currently registered.
1230      * It is also important to note that this method only returns the name
1231      * of a Logger, not a strong reference to the Logger itself.
1232      * The returned String does nothing to prevent the Logger from being
1233      * garbage collected. In particular, if the returned name is passed
1234      * to {@code LogManager.getLogger()}, then the caller must check the
1235      * return value from {@code LogManager.getLogger()} for null to properly
1236      * handle the case where the Logger has been garbage collected in the
1237      * time since its name was returned by this method.
1238      *
1239      * @return  enumeration of logger name strings
1240      */
1241     public Enumeration<String> getLoggerNames() {
1242         return getUserContext().getLoggerNames();
1243     }
1244 
1245     /**
1246      * Reinitialize the logging properties and reread the logging configuration.
1247      * <p>
1248      * The same rules are used for locating the configuration properties
1249      * as are used at startup.  So normally the logging properties will
1250      * be re-read from the same file that was used at startup.
1251      * <P>
1252      * Any log level definitions in the new configuration file will be
1253      * applied using Logger.setLevel(), if the target Logger exists.
1254      * <p>
1255      * Any {@linkplain #addConfigurationListener registered configuration
1256      * listener} will be invoked after the properties are read.
1257      *
1258      * @exception  SecurityException  if a security manager exists and if
1259      *             the caller does not have LoggingPermission("control").
1260      * @exception  IOException if there are IO problems reading the configuration.
1261      */
1262     public void readConfiguration() throws IOException, SecurityException {
1263         checkPermission();
1264 
1265         // if a configuration class is specified, load it and use it.
1266         String cname = System.getProperty("java.util.logging.config.class");
1267         if (cname != null) {
1268             try {
1269                 // Instantiate the named class.  It is its constructor's
1270                 // responsibility to initialize the logging configuration, by
1271                 // calling readConfiguration(InputStream) with a suitable stream.
1272                 try {
1273                     Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(cname);
1274                     clz.newInstance();
1275                     return;
1276                 } catch (ClassNotFoundException ex) {
1277                     Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(cname);
1278                     clz.newInstance();
1279                     return;
1280                 }
1281             } catch (Exception ex) {
1282                 System.err.println("Logging configuration class \"" + cname + "\" failed");
1283                 System.err.println("" + ex);
1284                 // keep going and useful config file.
1285             }
1286         }
1287 
1288         String fname = System.getProperty("java.util.logging.config.file");
1289         if (fname == null) {
1290             fname = System.getProperty("java.home");
1291             if (fname == null) {
1292                 throw new Error("Can't find java.home ??");
1293             }
1294             File f = new File(fname, "conf");
1295             f = new File(f, "logging.properties");
1296             fname = f.getCanonicalPath();
1297         }
1298         try (final InputStream in = new FileInputStream(fname)) {
1299             final BufferedInputStream bin = new BufferedInputStream(in);
1300             readConfiguration(bin);
1301         }
1302     }
1303 
1304     /**
1305      * Reset the logging configuration.
1306      * <p>
1307      * For all named loggers, the reset operation removes and closes
1308      * all Handlers and (except for the root logger) sets the level
1309      * to null.  The root logger's level is set to Level.INFO.
1310      *
1311      * @exception  SecurityException  if a security manager exists and if
1312      *             the caller does not have LoggingPermission("control").
1313      */
1314 
1315     public void reset() throws SecurityException {
1316         checkPermission();
1317 
1318         List<CloseOnReset> persistent;
1319 
1320         // We don't want reset() and readConfiguration()
1321         // to run in parallel
1322         configurationLock.lock();
1323         try {
1324             // install new empty properties
1325             props = new Properties();
1326             // make sure we keep the loggers persistent until reset is done.
1327             // Those are the loggers for which we previously created a
1328             // handler from the configuration, and we need to prevent them
1329             // from being gc'ed until those handlers are closed.
1330             persistent = new ArrayList<>(closeOnResetLoggers);
1331             closeOnResetLoggers.clear();
1332 
1333             // if reset has been called from shutdown-hook (Cleaner),
1334             // or if reset has been called from readConfiguration() which
1335             // already holds the lock and will change the state itself,
1336             // then do not change state here...
1337             if (globalHandlersState != STATE_SHUTDOWN &&
1338                 globalHandlersState != STATE_READING_CONFIG) {
1339                 // ...else user called reset()...
1340                 // Since we are doing a reset we no longer want to initialize
1341                 // the global handlers, if they haven't been initialized yet.
1342                 globalHandlersState = STATE_INITIALIZED;
1343             }
1344 
1345             for (LoggerContext cx : contexts()) {
1346                 resetLoggerContext(cx);
1347             }
1348 
1349             persistent.clear();
1350         } finally {
1351             configurationLock.unlock();
1352         }
1353     }
1354 
1355     private void resetLoggerContext(LoggerContext cx) {
1356         Enumeration<String> enum_ = cx.getLoggerNames();
1357         while (enum_.hasMoreElements()) {
1358             String name = enum_.nextElement();
1359             Logger logger = cx.findLogger(name);
1360             if (logger != null) {
1361                 resetLogger(logger);
1362             }
1363         }
1364     }
1365 
1366     private void closeHandlers(Logger logger) {
1367         Handler[] targets = logger.getHandlers();
1368         for (Handler h : targets) {
1369             logger.removeHandler(h);
1370             try {
1371                 h.close();
1372             } catch (Exception ex) {
1373                 // Problems closing a handler?  Keep going...
1374             }
1375         }
1376     }
1377 
1378     // Private method to reset an individual target logger.
1379     private void resetLogger(Logger logger) {
1380         // Close all the Logger handlers.
1381         closeHandlers(logger);
1382 
1383         // Reset Logger level
1384         String name = logger.getName();
1385         if (name != null && name.equals("")) {
1386             // This is the root logger.
1387             logger.setLevel(defaultLevel);
1388         } else {
1389             logger.setLevel(null);
1390         }
1391     }
1392 
1393     // get a list of whitespace separated classnames from a property.
1394     private String[] parseClassNames(String propertyName) {
1395         String hands = getProperty(propertyName);
1396         if (hands == null) {
1397             return new String[0];
1398         }
1399         hands = hands.trim();
1400         int ix = 0;
1401         final List<String> result = new ArrayList<>();
1402         while (ix < hands.length()) {
1403             int end = ix;
1404             while (end < hands.length()) {
1405                 if (Character.isWhitespace(hands.charAt(end))) {
1406                     break;
1407                 }
1408                 if (hands.charAt(end) == ',') {
1409                     break;
1410                 }
1411                 end++;
1412             }
1413             String word = hands.substring(ix, end);
1414             ix = end+1;
1415             word = word.trim();
1416             if (word.length() == 0) {
1417                 continue;
1418             }
1419             result.add(word);
1420         }
1421         return result.toArray(new String[result.size()]);
1422     }
1423 
1424     /**
1425      * Reinitialize the logging properties and reread the logging configuration
1426      * from the given stream, which should be in java.util.Properties format.
1427      * Any {@linkplain #addConfigurationListener registered configuration
1428      * listener} will be invoked after the properties are read.
1429      * <p>
1430      * Any log level definitions in the new configuration file will be
1431      * applied using Logger.setLevel(), if the target Logger exists.
1432      *
1433      * @param ins       stream to read properties from
1434      * @exception  SecurityException  if a security manager exists and if
1435      *             the caller does not have LoggingPermission("control").
1436      * @exception  IOException if there are problems reading from the stream.
1437      */
1438     public void readConfiguration(InputStream ins) throws IOException, SecurityException {
1439         checkPermission();
1440 
1441         // We don't want reset() and readConfiguration() to run
1442         // in parallel.
1443         configurationLock.lock();
1444         try {
1445             if (globalHandlersState == STATE_SHUTDOWN) {
1446                 // already in terminal state: don't even bother
1447                 // to read the configuration
1448                 return;
1449             }
1450 
1451             // change state to STATE_READING_CONFIG to signal reset() to not change it
1452             globalHandlersState = STATE_READING_CONFIG;
1453             try {
1454                 // reset configuration which leaves globalHandlersState at STATE_READING_CONFIG
1455                 // so that while reading configuration, any ongoing logging requests block and
1456                 // wait for the outcome (see the end of this try statement)
1457                 reset();
1458 
1459                 try {
1460                     // Load the properties
1461                     props.load(ins);
1462                 } catch (IllegalArgumentException x) {
1463                     // props.load may throw an IllegalArgumentException if the stream
1464                     // contains malformed Unicode escape sequences.
1465                     // We wrap that in an IOException as readConfiguration is
1466                     // specified to throw IOException if there are problems reading
1467                     // from the stream.
1468                     // Note: new IOException(x.getMessage(), x) allow us to get a more
1469                     // concise error message than new IOException(x);
1470                     throw new IOException(x.getMessage(), x);
1471                 }
1472 
1473                 // Instantiate new configuration objects.
1474                 String names[] = parseClassNames("config");
1475 
1476                 for (String word : names) {
1477                     try {
1478                         Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(word);
1479                         clz.newInstance();
1480                     } catch (Exception ex) {
1481                         System.err.println("Can't load config class \"" + word + "\"");
1482                         System.err.println("" + ex);
1483                         // ex.printStackTrace();
1484                     }
1485                 }
1486 
1487                 // Set levels on any pre-existing loggers, based on the new properties.
1488                 setLevelsOnExistingLoggers();
1489 
1490                 // Note that we need to reinitialize global handles when
1491                 // they are first referenced.
1492                 globalHandlersState = STATE_UNINITIALIZED;
1493             } catch (Throwable t) {
1494                 // If there were any trouble, then set state to STATE_INITIALIZED
1495                 // so that no global handlers reinitialization is performed on not fully
1496                 // initialized configuration.
1497                 globalHandlersState = STATE_INITIALIZED;
1498                 // re-throw
1499                 throw t;
1500             }
1501         } finally {
1502             configurationLock.unlock();
1503         }
1504 
1505         // should be called out of lock to avoid dead-lock situations
1506         // when user code is involved
1507         invokeConfigurationListeners();
1508     }
1509 
1510     /**
1511      * Get the value of a logging property.
1512      * The method returns null if the property is not found.
1513      * @param name      property name
1514      * @return          property value
1515      */
1516     public String getProperty(String name) {
1517         return props.getProperty(name);
1518     }
1519 
1520     // Package private method to get a String property.
1521     // If the property is not defined we return the given
1522     // default value.
1523     String getStringProperty(String name, String defaultValue) {
1524         String val = getProperty(name);
1525         if (val == null) {
1526             return defaultValue;
1527         }
1528         return val.trim();
1529     }
1530 
1531     // Package private method to get an integer property.
1532     // If the property is not defined or cannot be parsed
1533     // we return the given default value.
1534     int getIntProperty(String name, int defaultValue) {
1535         String val = getProperty(name);
1536         if (val == null) {
1537             return defaultValue;
1538         }
1539         try {
1540             return Integer.parseInt(val.trim());
1541         } catch (Exception ex) {
1542             return defaultValue;
1543         }
1544     }
1545 
1546     // Package private method to get a long property.
1547     // If the property is not defined or cannot be parsed
1548     // we return the given default value.
1549     long getLongProperty(String name, long defaultValue) {
1550         String val = getProperty(name);
1551         if (val == null) {
1552             return defaultValue;
1553         }
1554         try {
1555             return Long.parseLong(val.trim());
1556         } catch (Exception ex) {
1557             return defaultValue;
1558         }
1559     }
1560 
1561     // Package private method to get a boolean property.
1562     // If the property is not defined or cannot be parsed
1563     // we return the given default value.
1564     boolean getBooleanProperty(String name, boolean defaultValue) {
1565         String val = getProperty(name);
1566         if (val == null) {
1567             return defaultValue;
1568         }
1569         val = val.toLowerCase();
1570         if (val.equals("true") || val.equals("1")) {
1571             return true;
1572         } else if (val.equals("false") || val.equals("0")) {
1573             return false;
1574         }
1575         return defaultValue;
1576     }
1577 
1578     // Package private method to get a Level property.
1579     // If the property is not defined or cannot be parsed
1580     // we return the given default value.
1581     Level getLevelProperty(String name, Level defaultValue) {
1582         String val = getProperty(name);
1583         if (val == null) {
1584             return defaultValue;
1585         }
1586         Level l = Level.findLevel(val.trim());
1587         return l != null ? l : defaultValue;
1588     }
1589 
1590     // Package private method to get a filter property.
1591     // We return an instance of the class named by the "name"
1592     // property. If the property is not defined or has problems
1593     // we return the defaultValue.
1594     Filter getFilterProperty(String name, Filter defaultValue) {
1595         String val = getProperty(name);
1596         try {
1597             if (val != null) {
1598                 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(val);
1599                 return (Filter) clz.newInstance();
1600             }
1601         } catch (Exception ex) {
1602             // We got one of a variety of exceptions in creating the
1603             // class or creating an instance.
1604             // Drop through.
1605         }
1606         // We got an exception.  Return the defaultValue.
1607         return defaultValue;
1608     }
1609 
1610 
1611     // Package private method to get a formatter property.
1612     // We return an instance of the class named by the "name"
1613     // property. If the property is not defined or has problems
1614     // we return the defaultValue.
1615     Formatter getFormatterProperty(String name, Formatter defaultValue) {
1616         String val = getProperty(name);
1617         try {
1618             if (val != null) {
1619                 Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(val);
1620                 return (Formatter) clz.newInstance();
1621             }
1622         } catch (Exception ex) {
1623             // We got one of a variety of exceptions in creating the
1624             // class or creating an instance.
1625             // Drop through.
1626         }
1627         // We got an exception.  Return the defaultValue.
1628         return defaultValue;
1629     }
1630 
1631     // Private method to load the global handlers.
1632     // We do the real work lazily, when the global handlers
1633     // are first used.
1634     private void initializeGlobalHandlers() {
1635         int state = globalHandlersState;
1636         if (state == STATE_INITIALIZED ||
1637             state == STATE_SHUTDOWN) {
1638             // Nothing to do: return.
1639             return;
1640         }
1641 
1642         // If we have not initialized global handlers yet (or need to
1643         // reinitialize them), lets do it now (this case is indicated by
1644         // globalHandlersState == STATE_UNINITIALIZED).
1645         // If we are in the process of initializing global handlers we
1646         // also need to lock & wait (this case is indicated by
1647         // globalHandlersState == STATE_INITIALIZING).
1648         // If we are in the process of reading configuration we also need to
1649         // wait to see what the outcome will be (this case
1650         // is indicated by globalHandlersState == STATE_READING_CONFIG)
1651         // So in either case we need to wait for the lock.
1652         configurationLock.lock();
1653         try {
1654             if (globalHandlersState != STATE_UNINITIALIZED) {
1655                 return; // recursive call or nothing to do
1656             }
1657             // set globalHandlersState to STATE_INITIALIZING first to avoid
1658             // getting an infinite recursion when loadLoggerHandlers(...)
1659             // is going to call addHandler(...)
1660             globalHandlersState = STATE_INITIALIZING;
1661             try {
1662                 loadLoggerHandlers(rootLogger, null, "handlers");
1663             } finally {
1664                 globalHandlersState = STATE_INITIALIZED;
1665             }
1666         } finally {
1667             configurationLock.unlock();
1668         }
1669     }
1670 
1671     static final Permission controlPermission =
1672             new LoggingPermission("control", null);
1673     static final Permission demandLoggerPermission =
1674             new LoggingPermission("demandLogger", null);
1675 
1676     void checkPermission() {
1677         SecurityManager sm = System.getSecurityManager();
1678         if (sm != null)
1679             sm.checkPermission(controlPermission);
1680     }
1681 
1682     /**
1683      * Check that the current context is trusted to modify the logging
1684      * configuration.  This requires LoggingPermission("control").
1685      * <p>
1686      * If the check fails we throw a SecurityException, otherwise
1687      * we return normally.
1688      *
1689      * @exception  SecurityException  if a security manager exists and if
1690      *             the caller does not have LoggingPermission("control").
1691      */
1692     public void checkAccess() throws SecurityException {
1693         checkPermission();
1694     }
1695 
1696     // Nested class to represent a node in our tree of named loggers.
1697     private static class LogNode {
1698         HashMap<String,LogNode> children;
1699         LoggerWeakRef loggerRef;
1700         LogNode parent;
1701         final LoggerContext context;
1702 
1703         LogNode(LogNode parent, LoggerContext context) {
1704             this.parent = parent;
1705             this.context = context;
1706         }
1707 
1708         // Recursive method to walk the tree below a node and set
1709         // a new parent logger.
1710         void walkAndSetParent(Logger parent) {
1711             if (children == null) {
1712                 return;
1713             }
1714             for (LogNode node : children.values()) {
1715                 LoggerWeakRef ref = node.loggerRef;
1716                 Logger logger = (ref == null) ? null : ref.get();
1717                 if (logger == null) {
1718                     node.walkAndSetParent(parent);
1719                 } else {
1720                     doSetParent(logger, parent);
1721                 }
1722             }
1723         }
1724     }
1725 
1726     // We use a subclass of Logger for the root logger, so
1727     // that we only instantiate the global handlers when they
1728     // are first needed.
1729     private final class RootLogger extends Logger {
1730         private RootLogger() {
1731             // We do not call the protected Logger two args constructor here,
1732             // to avoid calling LogManager.getLogManager() from within the
1733             // RootLogger constructor.
1734             super("", null, null, LogManager.this, true);
1735         }
1736 
1737         @Override
1738         public void log(LogRecord record) {
1739             // Make sure that the global handlers have been instantiated.
1740             initializeGlobalHandlers();
1741             super.log(record);
1742         }
1743 
1744         @Override
1745         public void addHandler(Handler h) {
1746             initializeGlobalHandlers();
1747             super.addHandler(h);
1748         }
1749 
1750         @Override
1751         public void removeHandler(Handler h) {
1752             initializeGlobalHandlers();
1753             super.removeHandler(h);
1754         }
1755 
1756         @Override
1757         Handler[] accessCheckedHandlers() {
1758             initializeGlobalHandlers();
1759             return super.accessCheckedHandlers();
1760         }
1761     }
1762 
1763 
1764     // Private method to be called when the configuration has
1765     // changed to apply any level settings to any pre-existing loggers.
1766     private void setLevelsOnExistingLoggers() {
1767         Enumeration<?> enum_ = props.propertyNames();
1768         while (enum_.hasMoreElements()) {
1769             String key = (String)enum_.nextElement();
1770             if (!key.endsWith(".level")) {
1771                 // Not a level definition.
1772                 continue;
1773             }
1774             int ix = key.length() - 6;
1775             String name = key.substring(0, ix);
1776             Level level = getLevelProperty(key, null);
1777             if (level == null) {
1778                 System.err.println("Bad level value for property: " + key);
1779                 continue;
1780             }
1781             for (LoggerContext cx : contexts()) {
1782                 Logger l = cx.findLogger(name);
1783                 if (l == null) {
1784                     continue;
1785                 }
1786                 l.setLevel(level);
1787             }
1788         }
1789     }
1790 
1791     // Management Support
1792     private static LoggingMXBean loggingMXBean = null;
1793     /**
1794      * String representation of the
1795      * {@link javax.management.ObjectName} for the management interface
1796      * for the logging facility.
1797      *
1798      * @see java.lang.management.PlatformLoggingMXBean
1799      * @see java.util.logging.LoggingMXBean
1800      *
1801      * @since 1.5
1802      */
1803     public final static String LOGGING_MXBEAN_NAME
1804         = "java.util.logging:type=Logging";
1805 
1806     /**
1807      * Returns {@code LoggingMXBean} for managing loggers.
1808      * An alternative way to manage loggers is through the
1809      * {@link java.lang.management.PlatformLoggingMXBean} interface
1810      * that can be obtained by calling:
1811      * <pre>
1812      *     PlatformLoggingMXBean logging = {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
1813      *         ManagementFactory.getPlatformMXBean}(PlatformLoggingMXBean.class);
1814      * </pre>
1815      *
1816      * @return a {@link LoggingMXBean} object.
1817      *
1818      * @see java.lang.management.PlatformLoggingMXBean
1819      * @since 1.5
1820      */
1821     public static synchronized LoggingMXBean getLoggingMXBean() {
1822         if (loggingMXBean == null) {
1823             loggingMXBean =  new Logging();
1824         }
1825         return loggingMXBean;
1826     }
1827 
1828     /**
1829      * Adds a configuration listener to be invoked each time the logging
1830      * configuration is read.
1831      * If the listener is already registered the method does nothing.
1832      * <p>
1833      * The listener is invoked with privileges that are restricted by the
1834      * calling context of this method.
1835      * The order in which the listeners are invoked is unspecified.
1836      * <p>
1837      * It is recommended that listeners do not throw errors or exceptions.
1838      *
1839      * If a listener terminates with an uncaught error or exception then
1840      * the first exception will be propagated to the caller of
1841      * {@link #readConfiguration()} (or {@link #readConfiguration(java.io.InputStream)})
1842      * after all listeners have been invoked.
1843      *
1844      * @implNote If more than one listener terminates with an uncaught error or
1845      * exception, an implementation may record the additional errors or
1846      * exceptions as {@linkplain Throwable#addSuppressed(java.lang.Throwable)
1847      * suppressed exceptions}.
1848      *
1849      * @param listener A configuration listener that will be invoked after the
1850      *        configuration changed.
1851      * @return This LogManager.
1852      * @throws SecurityException if a security manager exists and if the
1853      * caller does not have LoggingPermission("control").
1854      * @throws NullPointerException if the listener is null.
1855      *
1856      * @since 1.9
1857      */
1858     public LogManager addConfigurationListener(Runnable listener) {
1859         final Runnable r = Objects.requireNonNull(listener);
1860         checkPermission();
1861         final SecurityManager sm = System.getSecurityManager();
1862         final AccessControlContext acc =
1863                 sm == null ? null : AccessController.getContext();
1864         final PrivilegedAction<Void> pa =
1865                 acc == null ? null : () -> { r.run() ; return null; };
1866         final Runnable pr =
1867                 acc == null ? r : () -> AccessController.doPrivileged(pa, acc);
1868         // Will do nothing if already registered.
1869         listeners.putIfAbsent(r, pr);
1870         return this;
1871     }
1872 
1873     /**
1874      * Removes a previously registered configuration listener.
1875      *
1876      * Returns silently if the listener is not found.
1877      *
1878      * @param listener the configuration listener to remove.
1879      * @throws NullPointerException if the listener is null.
1880      * @throws SecurityException if a security manager exists and if the
1881      * caller does not have LoggingPermission("control").
1882      *
1883      * @since 1.9
1884      */
1885     public void removeConfigurationListener(Runnable listener) {
1886         final Runnable key = Objects.requireNonNull(listener);
1887         checkPermission();
1888         listeners.remove(key);
1889     }
1890 
1891     private void invokeConfigurationListeners() {
1892         Throwable t = null;
1893 
1894         // We're using an IdentityHashMap because we want to compare
1895         // keys using identity (==).
1896         // We don't want to loop within a block synchronized on 'listeners'
1897         // to avoid invoking listeners from yet another synchronized block.
1898         // So we're taking a snapshot of the values list to avoid the risk of
1899         // ConcurrentModificationException while looping.
1900         //
1901         for (Runnable c : listeners.values().toArray(new Runnable[0])) {
1902             try {
1903                 c.run();
1904             } catch (ThreadDeath death) {
1905                 throw death;
1906             } catch (Error | RuntimeException x) {
1907                 if (t == null) t = x;
1908                 else t.addSuppressed(x);
1909             }
1910         }
1911         // Listeners are not supposed to throw exceptions, but if that
1912         // happens, we will rethrow the first error or exception that is raised
1913         // after all listeners have been invoked.
1914         if (t instanceof Error) throw (Error)t;
1915         if (t instanceof RuntimeException) throw (RuntimeException)t;
1916     }
1917 
1918     /**
1919      * Demands a logger suitable for given caller.
1920      * <p>
1921      * If a named logger suitable for the given caller is found
1922      * returns it.
1923      * Otherwise, creates a new logger suitable for the given caller.
1924      *
1925      * @param name   The logger name.
1926      * @param caller The caller on which behalf the logger is created/retrieved.
1927      * @return A logger for the given caller.
1928      *
1929      * @throws SecurityException if the calling code doesn't have the
1930      *        {@link LoggingPermission LoggingPermission("demandLogger", null)}.
1931      * @since 9
1932      */
1933     public static Logger demandLoggerFor(String name, /* Module */ Class<?> caller) {
1934         SecurityManager sm = System.getSecurityManager();
1935         if (sm != null) {
1936             sm.checkPermission(demandLoggerPermission);
1937         }
1938         if (caller.getClassLoader() == null) {
1939             return LogManager.getLogManager().demandSystemLogger(name,
1940                 Logger.SYSTEM_LOGGER_RB_NAME, caller);
1941         } else {
1942             return LogManager.getLogManager().demandLogger(name, null, caller);
1943         }
1944     }
1945 
1946 }