LOG4J2-3121 config modified at run-time may trigger incomplete MBean re-initialization due to InstanceAlreadyExistsException (#547)

* LOG4J2-3121: log4j2 config modified at run-time may trigger incomplete MBean re-initialization due to InstanceAlreadyExistsException

* LOG4J2-3121: Update for codestyle

* LOG4J2-3121: Updated changes.xml with bugfix info

Co-authored-by: Markus Spann <Markus.Spann@baaderbank.de>
Co-authored-by: Volkan Yazıcı <volkan.yazici@gmail.com>
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 26cb705..df3bb71 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
@@ -387,7 +387,15 @@
 
     private static void register(final MBeanServer mbs, final Object mbean, final ObjectName objectName)
             throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {
+        if (mbs.isRegistered(objectName)) {
+            try {
+                mbs.unregisterMBean(objectName);
+            } catch (MBeanRegistrationException | InstanceNotFoundException ex) {
+                LOGGER.trace("Failed to unregister MBean {}", objectName);
+            }
+        }
         LOGGER.debug("Registering MBean {}", objectName);
         mbs.registerMBean(mbean, objectName);
     }
+
 }
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 00f3a5e..692ee9a 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -214,6 +214,8 @@
         Allow a PatternSelector to be specified on GelfLayout.
       </action>
       <!-- FIXES -->
+      <action issue="LOG4J2-3121" dev="ggregory" type="fix" due-to="Markus Spann">
+          log4j2 config modified at run-time may trigger incomplete MBean re-initialization due to InstanceAlreadyExistsException.
       <action issue="LOG4J2-3107" dev="vy" type="fix" due-to="Markus Spann">
         SmtpManager.createManagerName ignores port.
       </action>