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