Avoid `java.management` dependency when JMX is disabled (#2775)

Co-authored-by: Piotr P. Karwasz <piotr.github@karwasz.org>
diff --git a/log4j-core/pom.xml b/log4j-core/pom.xml
index 05a6de6..646f0c4 100644
--- a/log4j-core/pom.xml
+++ b/log4j-core/pom.xml
@@ -70,8 +70,12 @@
       javax.lang.model.*;resolution:=optional,
       javax.tools;resolution:=optional,
       <!-- `java.sql`, which depends on `java.logging` is optional -->
+      java.sql;resolution:=optional,
       javax.sql;resolution:=optional,
       java.util.logging;resolution:=optional,
+      <!-- `java.management` is optional -->
+      java.lang.management;resolution:=optional,
+      javax.management.*;resolution:=optional,
       <!-- `java.naming` is optional -->
       javax.naming;resolution:=optional
     </bnd-extra-package-options>
@@ -88,6 +92,7 @@
       com.fasterxml.jackson.databind;transitive=false,
       com.fasterxml.jackson.dataformat.xml;transitive=false,
       com.fasterxml.jackson.dataformat.yaml;transitive=false,
+      java.management;transitive=false;static=true,
       java.naming;transitive=false,
       org.apache.commons.csv;transitive=false,
       org.fusesource.jansi;transitive=false,
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java
index abc1764..07cd2d1 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/LoggerContext.java
@@ -16,6 +16,7 @@
  */
 package org.apache.logging.log4j.core;
 
+import static org.apache.logging.log4j.core.jmx.internal.JmxUtil.isJmxDisabled;
 import static org.apache.logging.log4j.core.util.ShutdownCallbackRegistry.SHUTDOWN_HOOK_MARKER;
 
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@@ -370,12 +371,7 @@
             }
 
             this.setStopping();
-            try {
-                Server.unregisterLoggerContext(getName()); // LOG4J2-406, LOG4J2-500
-            } catch (final LinkageError | Exception e) {
-                // LOG4J2-1506 Hello Android, GAE
-                LOGGER.error("Unable to unregister MBeans", e);
-            }
+            unregisterJmxBeans();
             if (shutdownCallback != null) {
                 shutdownCallback.cancel();
                 shutdownCallback = null;
@@ -407,6 +403,17 @@
         return true;
     }
 
+    private void unregisterJmxBeans() {
+        if (!isJmxDisabled()) {
+            try {
+                Server.unregisterLoggerContext(getName()); // LOG4J2-406, LOG4J2-500
+            } catch (final LinkageError | Exception error) {
+                // LOG4J2-1506 Hello Android, GAE
+                LOGGER.error("Unable to unregister MBeans", error);
+            }
+        }
+    }
+
     /**
      * Gets the name.
      *
@@ -638,12 +645,8 @@
 
             firePropertyChangeEvent(new PropertyChangeEvent(this, PROPERTY_CONFIG, prev, config));
 
-            try {
-                Server.reregisterMBeansAfterReconfigure();
-            } catch (final LinkageError | Exception e) {
-                // LOG4J2-716: Android has no java.lang.management
-                LOGGER.error("Could not reconfigure JMX", e);
-            }
+            registerJmxBeans();
+
             // AsyncLoggers update their nanoClock when the configuration changes
             Log4jLogEvent.setNanoClock(configuration.getNanoClock());
 
@@ -653,6 +656,17 @@
         }
     }
 
+    private static void registerJmxBeans() {
+        if (!isJmxDisabled()) {
+            try {
+                Server.reregisterMBeansAfterReconfigure();
+            } catch (final LinkageError | Exception error) {
+                // LOG4J2-716: Android has no java.lang.management
+                LOGGER.error("Could not reconfigure JMX", error);
+            }
+        }
+    }
+
     private void firePropertyChangeEvent(final PropertyChangeEvent event) {
         for (final PropertyChangeListener listener : propertyChangeListeners) {
             listener.propertyChange(event);
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
index d3284f9..d5adfb1 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
@@ -16,6 +16,8 @@
  */
 package org.apache.logging.log4j.core.jmx;
 
+import static org.apache.logging.log4j.core.jmx.internal.JmxUtil.isJmxDisabled;
+
 import java.lang.management.ManagementFactory;
 import java.util.List;
 import java.util.Map;
@@ -58,7 +60,6 @@
      */
     public static final String DOMAIN = "org.apache.logging.log4j2";
 
-    private static final String PROPERTY_DISABLE_JMX = "log4j2.disable.jmx";
     private static final String PROPERTY_ASYNC_NOTIF = "log4j2.jmx.notify.async";
     private static final String THREAD_NAME_PREFIX = "jmx.notif";
     private static final StatusLogger LOGGER = StatusLogger.getLogger();
@@ -126,10 +127,6 @@
         return sb.toString();
     }
 
-    private static boolean isJmxDisabled() {
-        return PropertiesUtil.getProperties().getBooleanProperty(PROPERTY_DISABLE_JMX, true);
-    }
-
     public static void reregisterMBeansAfterReconfigure() {
         // avoid creating Platform MBean Server if JMX disabled
         if (isJmxDisabled()) {
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/internal/JmxUtil.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/internal/JmxUtil.java
new file mode 100644
index 0000000..3f76c99
--- /dev/null
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/internal/JmxUtil.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.logging.log4j.core.jmx.internal;
+
+import org.apache.logging.log4j.util.PropertiesUtil;
+
+// WARNING!
+// This class must be free of any dependencies to the `java.management` module!
+// Otherwise, `isJmxDisabled()` call sites would unnecessarily require the `java.management` module.
+// For details, see: https://github.com/apache/logging-log4j2/issues/2774
+
+public final class JmxUtil {
+
+    public static boolean isJmxDisabled() {
+        return PropertiesUtil.getProperties().getBooleanProperty("log4j2.disable.jmx", true);
+    }
+
+    private JmxUtil() {}
+}
diff --git a/src/changelog/.2.x.x/fix_jmx_module_dep.xml b/src/changelog/.2.x.x/fix_jmx_module_dep.xml
new file mode 100644
index 0000000..27d0f4c
--- /dev/null
+++ b/src/changelog/.2.x.x/fix_jmx_module_dep.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns="https://logging.apache.org/xml/ns"
+       xsi:schemaLocation="https://logging.apache.org/xml/ns https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
+       type="fixed">
+  <issue id="2775" link="https://github.com/apache/logging-log4j2/pull/2775"/>
+  <description format="asciidoc">Fix requirement on the `java.management` module when JMX is disabled, which is the default</description>
+</entry>