@Override
  public void stop() {
    LOGGER.debug("Stopping LoggerContext[name={}, {}]...", getName(), this);
    configLock.lock();
    try {
      if (this.isStopped()) {
        return;
      }

      this.setStopping();
      try {
        Server.unregisterLoggerContext(getName()); // LOG4J2-406, LOG4J2-500
      } catch (final Exception ex) {
        LOGGER.error("Unable to unregister MBeans", ex);
      }
      if (shutdownCallback != null) {
        shutdownCallback.cancel();
        shutdownCallback = null;
      }
      final Configuration prev = configuration;
      configuration = NULL_CONFIGURATION;
      updateLoggers();
      prev.stop();
      externalContext = null;
      LogManager.getFactory().removeContext(this);
      this.setStopped();
    } finally {
      configLock.unlock();
    }
    LOGGER.debug("Stopped LoggerContext[name={}, {}]...", getName(), this);
  }
  /**
   * Sets the Configuration to be used.
   *
   * @param config The new Configuration.
   * @return The previous Configuration.
   */
  private Configuration setConfiguration(final Configuration config) {
    Objects.requireNonNull(config, "No Configuration was provided");
    configLock.lock();
    try {
      final Configuration prev = this.configuration;
      config.addListener(this);
      final ConcurrentMap<String, String> map =
          config.getComponent(Configuration.CONTEXT_PROPERTIES);

      try { // LOG4J2-719 network access may throw android.os.NetworkOnMainThreadException
        map.putIfAbsent("hostName", NetUtils.getLocalHostname());
      } catch (final Exception ex) {
        LOGGER.debug("Ignoring {}, setting hostName to 'unknown'", ex.toString());
        map.putIfAbsent("hostName", "unknown");
      }
      map.putIfAbsent("contextName", contextName);
      config.start();
      this.configuration = config;
      updateLoggers();
      if (prev != null) {
        prev.removeListener(this);
        prev.stop();
      }

      firePropertyChangeEvent(new PropertyChangeEvent(this, PROPERTY_CONFIG, prev, config));

      try {
        Server.reregisterMBeansAfterReconfigure();
      } catch (final Throwable t) {
        // LOG4J2-716: Android has no java.lang.management
        LOGGER.error("Could not reconfigure JMX", t);
      }
      Log4jLogEvent.setNanoClock(NanoClockFactory.createNanoClock());
      AsyncLogger.setNanoClock(NanoClockFactory.createNanoClock());
      return prev;
    } finally {
      configLock.unlock();
    }
  }