If the MBean already exists, register metrics immediately. Otherwise register an MBean registration listener
with the MBeanServer and register metrics when/if the MBean becomes available.
508857
private void registerMetricsEventually(String key, String value, BiConsumer<ObjectName, Iterable<Tag>> perObject) {
        if (getJmxDomain() != null) {
            try {
                Set<ObjectName> objectNames = this.mBeanServer.queryNames(new ObjectName(getJmxDomain() + ":" + key + "=" + value + ",name=*"), null);
                if (!objectNames.isEmpty()) {
                    // MBean is present, so we can register metrics now.
                    objectNames.forEach(objectName -> perObject.accept(objectName, Tags.concat(tags, nameTag(objectName))));
                    return;
                }
            } catch (MalformedObjectNameException e) {
                // should never happen
                throw new RuntimeException("Error registering Tomcat JMX based metrics", e);
            }
        }

        // MBean isn't yet registered, so we'll set up a notification to wait for them to be present and register
        // metrics later.
        NotificationListener notificationListener = new NotificationListener() {
            @Override
            public void handleNotification(Notification notification, Object handback) {
                MBeanServerNotification mBeanServerNotification = (MBeanServerNotification) notification;
                ObjectName objectName = mBeanServerNotification.getMBeanName();
                perObject.accept(objectName, Tags.concat(tags, nameTag(objectName)));
                try {
                    mBeanServer.removeNotificationListener(MBeanServerDelegate.DELEGATE_NAME, this);
                } catch (InstanceNotFoundException | ListenerNotFoundException ex) {
                    throw new RuntimeException(ex);
                }
            }
        };

        NotificationFilter notificationFilter = (NotificationFilter) notification -> {
            if (!MBeanServerNotification.REGISTRATION_NOTIFICATION.equals(notification.getType())) {
                return false;
            }

            // we can safely downcast now
            ObjectName objectName = ((MBeanServerNotification) notification).getMBeanName();
            return objectName.getDomain().equals(getJmxDomain()) && objectName.getKeyProperty(key).equals(value);
        };

        try {
            mBeanServer.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, notificationListener, notificationFilter, null);
        } catch (InstanceNotFoundException e) {
            // should never happen
            throw new RuntimeException("Error registering MBean listener", e);
        }
    }
47424
def register(metric_name)
      metric_name = metric_name.to_s
      metric_exists = self.for(metric_name).present?

      if metric_exists
        raise(
          MetricAlreadyRegistered,
          "There's a metric already registered with the name `:#{metric_name}`, must be unique"
        )
      end

      metric_manifest = MetricManifest.new(metric_name: metric_name)

      yield(metric_manifest)

      metric_manifest.validate!

      metrics_manifests << metric_manifest
    end
867819
private void registerQueryMBeans(ComponentRegistry cr, Configuration cfg, SearchIntegrator searchIntegrator) {
      AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache();
      // Resolve MBean server instance
      GlobalJmxStatisticsConfiguration jmxConfig = cr.getGlobalComponentRegistry().getGlobalConfiguration().globalJmxStatistics();
      if (!jmxConfig.enabled())
         return;
      if (mbeanServer == null) {
         mbeanServer = JmxUtil.lookupMBeanServer(jmxConfig.mbeanServerLookup(), jmxConfig.properties());
      }

      // Resolve jmx domain to use for query MBeans
      String queryGroupName = getQueryGroupName(jmxConfig.cacheManagerName(), cache.getName());
      String jmxDomain = JmxUtil.buildJmxDomain(jmxConfig.domain(), mbeanServer, queryGroupName);

      // Register query statistics MBean, but only enable it if Infinispan config says so
      try {
         ObjectName statsObjName = new ObjectName(jmxDomain + ":" + queryGroupName + ",component=Statistics");

         InfinispanQueryStatisticsInfo stats = new InfinispanQueryStatisticsInfo(searchIntegrator, statsObjName);
         stats.setStatisticsEnabled(cfg.jmxStatistics().enabled());

         JmxUtil.registerMBean(stats, statsObjName, mbeanServer);

         cr.registerComponent(stats, InfinispanQueryStatisticsInfo.class);
      } catch (Exception e) {
         throw new CacheException("Unable to register query statistics MBean", e);
      }

      // Register mass indexer MBean, picking metadata from repo
      ManageableComponentMetadata massIndexerCompMetadata = cr.getGlobalComponentRegistry().getComponentMetadataRepo()
            .findComponentMetadata(MassIndexer.class)
            .toManageableComponentMetadata();
      try {
         KeyTransformationHandler keyTransformationHandler = ComponentRegistryUtils.getKeyTransformationHandler(cache);
         TimeService timeService = ComponentRegistryUtils.getTimeService(cache);
         // TODO: MassIndexer should be some kind of query cache component?
         DistributedExecutorMassIndexer massIndexer = new DistributedExecutorMassIndexer(cache, searchIntegrator, keyTransformationHandler, timeService);
         ResourceDMBean mbean = new ResourceDMBean(massIndexer, massIndexerCompMetadata);
         ObjectName massIndexerObjName = new ObjectName(jmxDomain + ":"
               + queryGroupName + ",component=" + massIndexerCompMetadata.getJmxObjectName());
         JmxUtil.registerMBean(mbean, massIndexerObjName, mbeanServer);
      } catch (Exception e) {
         throw new CacheException("Unable to create MassIndexer MBean", e);
      }
   }
227620
def register(listener):
    
    if not isinstance(listener, _EventListener):
        raise TypeError("Listeners for %s must be either a "
                        "CommandListener, ServerHeartbeatListener, "
                        "ServerListener, or TopologyListener." % (listener,))
    if isinstance(listener, CommandListener):
        _LISTENERS.command_listeners.append(listener)
    if isinstance(listener, ServerHeartbeatListener):
        _LISTENERS.server_heartbeat_listeners.append(listener)
    if isinstance(listener, ServerListener):
        _LISTENERS.server_listeners.append(listener)
    if isinstance(listener, TopologyListener):
        _LISTENERS.topology_listeners.append(listener)
860811
private static synchronized void registerListener() {

        if (!m_listenerRegistered) {
            OpenCms.getEventManager().addCmsEventListener(
                new CmsIconUtil(),
                new int[] {I_CmsEventListener.EVENT_CLEAR_CACHES});
            m_listenerRegistered = true;
        }
    }
589835
public void setMetricRegistry(Object metricRegistry)
   {
      if (metricsTrackerFactory != null) {
         throw new IllegalStateException("cannot use setMetricRegistry() and setMetricsTrackerFactory() together");
      }

      if (metricRegistry != null) {
         metricRegistry = getObjectOrPerformJndiLookup(metricRegistry);

         if (!safeIsAssignableFrom(metricRegistry, "com.codahale.metrics.MetricRegistry")
             && !(safeIsAssignableFrom(metricRegistry, "io.micrometer.core.instrument.MeterRegistry"))) {
            throw new IllegalArgumentException("Class must be instance of com.codahale.metrics.MetricRegistry or io.micrometer.core.instrument.MeterRegistry");
         }
      }

      this.metricRegistry = metricRegistry;
   }
1337505
private void initMBean()  {
        try {
            registerMBean(this,getObjectName());
        } catch (InstanceAlreadyExistsException exp) {
            // This is no problem, since this MBeanServerHandlerMBean holds only global information
            // with no special state (so all instances of this MBean behave similar)
            // This exception can happen, when multiple servlets get registered within the same JVM
        } catch (MalformedObjectNameException e) {
            // Cannot happen, otherwise this is a bug. We should be always provide our own name in correct
            // form.
            throw new IllegalStateException("Internal Error: Own ObjectName " + getObjectName() + " is malformed",e);
        } catch (NotCompliantMBeanException e) {
            // Same here
            throw new IllegalStateException("Internal Error: " + this.getClass().getName() + " is not a compliant MBean",e);
        }
    }
526391
public Subscription register(final Object mBean, final String name){
        try {
            if (mbeanSupport.get()) {
                final ObjectName objectName = new ObjectName(name);
                server.registerMBean(mBean, objectName);
                return new Subscription() {
                    @Override
                    public void unsubscribe() {
                        try {
                            server.unregisterMBean(objectName);
                        } catch (JMException e) {
                            throw new RuntimeException("Can not unsubscribe!", e);
                        }
                    }
                };
            } else {
                return new Subscription() {
                    @Override
                    public void unsubscribe() {
                    }
                };
            }
        } catch (Exception e) {
            throw new RuntimeException("Can not register MBean!", e);
        }
    }
1189196
def register_model_once(cls, ModelClass, **kwargs):
        
        if cls._static_registry.get_for_model(ModelClass) is None:
            logger.warn("Model is already registered with {0}: '{1}'"
                        .format(cls, ModelClass))
        else:
            cls.register_model.register(ModelClass, **kwargs)
447623
public static void registerMBean(String packageName, String type, String name, Object mbean) {
		try {
			String pkg = defaultString(packageName, mbean.getClass().getPackage().getName());
			MBeanServer server = ManagementFactory.getPlatformMBeanServer();
			ObjectName on = new ObjectName(pkg + ":type=" + type + ",name=" + name);
			if (server.isRegistered(on)) {
				Say.debug("MBean with type {type} and name {name} for {package} has already been defined, ignoring", type, name, pkg);
			}
			else {
				server.registerMBean(mbean, on);
			}
		}
		catch (Exception ex) {
			Say.warn("MBean could not be registered", ex);
		}
	}
163857
public static void register(String name, Object instance) {
    try {
      Class<Object> mbeanInterface = guessMBeanInterface(instance);
      ManagementFactory.getPlatformMBeanServer().registerMBean(new StandardMBean(instance, mbeanInterface), new ObjectName(name));

    } catch (MalformedObjectNameException | NotCompliantMBeanException | InstanceAlreadyExistsException | MBeanRegistrationException e) {
      throw new IllegalStateException("Can not register MBean [" + name + "]", e);
    }
  }
709177
protected void addMetric(String name, Metric metric) {
		if (metric == null) {
			LOG.warn("Ignoring attempted registration of a metric due to being null for name {}.", name);
			return;
		}
		// add the metric only if the group is still open
		synchronized (this) {
			if (!closed) {
				// immediately put without a 'contains' check to optimize the common case (no collision)
				// collisions are resolved later
				Metric prior = metrics.put(name, metric);

				// check for collisions with other metric names
				if (prior == null) {
					// no other metric with this name yet

					if (groups.containsKey(name)) {
						// we warn here, rather than failing, because metrics are tools that should not fail the
						// program when used incorrectly
						LOG.warn("Name collision: Adding a metric with the same name as a metric subgroup: '" +
								name + "'. Metric might not get properly reported. " + Arrays.toString(scopeComponents));
					}

					registry.register(metric, name, this);
				}
				else {
					// we had a collision. put back the original value
					metrics.put(name, prior);

					// we warn here, rather than failing, because metrics are tools that should not fail the
					// program when used incorrectly
					LOG.warn("Name collision: Group already contains a Metric with the name '" +
							name + "'. Metric will not be reported." + Arrays.toString(scopeComponents));
				}
			}
		}
	}
910685
private void registerPerformanceMonitor(String beanName,
                                            BeanDefinitionRegistry registry) {

        String perfMonitorName = beanName + "PerformanceMonitor";
        if (!registry.containsBeanDefinition(perfMonitorName))  {
            BeanDefinitionBuilder initializer =
                BeanDefinitionBuilder.rootBeanDefinition(PerformanceMonitorBean.class);
            registry.registerBeanDefinition(perfMonitorName, initializer.getBeanDefinition());
        }
    }
519727
protected void registerUnregisterJMX(boolean doRegister) {
		if (this.mbs == null ){ // this way makes it easier for mocking.
			this.mbs = ManagementFactory.getPlatformMBeanServer();
		}
		try {
			String suffix = "";

			if (this.config.getPoolName()!=null){
				suffix="-"+this.config.getPoolName();
			}

			ObjectName name = new ObjectName(MBEAN_BONECP +suffix);
			ObjectName configname = new ObjectName(MBEAN_CONFIG + suffix);


			if (doRegister){
				if (!this.mbs.isRegistered(name)){
					this.mbs.registerMBean(this.statistics, name);
				}
				if (!this.mbs.isRegistered(configname)){
					this.mbs.registerMBean(this.config, configname);
				}
			} else {
				if (this.mbs.isRegistered(name)){
					this.mbs.unregisterMBean(name);
				}
				if (this.mbs.isRegistered(configname)){
					this.mbs.unregisterMBean(configname);
				}
			}
		} catch (Exception e) {
			logger.error("Unable to start/stop JMX", e);
		}
	}
747011
private void sendRegisterRequest() {
    Metrics.MetricPublisher publisher = Metrics.MetricPublisher.newBuilder().
        setHostname(hostname).
        setPort(instance.getInfo().getTaskId()).
        setComponentName(instance.getInfo().getComponentName()).
        setInstanceId(instance.getInstanceId()).
        setInstanceIndex(instance.getInfo().getComponentIndex()).
        build();
    Metrics.MetricPublisherRegisterRequest request =
        Metrics.MetricPublisherRegisterRequest.newBuilder().
            setPublisher(publisher).
            build();

    // The timeout would be the reconnect-interval-seconds
    sendRequest(request, null,
        Metrics.MetricPublisherRegisterResponse.newBuilder(),
        systemConfig.getInstanceReconnectMetricsmgrInterval());
  }
1057545
def register(self, request_class: Request, handler_factory: Callable[[], Handler]) -> None:
        
        key = request_class.__name__
        is_command = request_class.is_command()
        is_event = request_class.is_event()
        is_present = key in self._registry
        if is_command and is_present:
            raise ConfigurationException("A handler for this request has already been registered")
        elif is_event and is_present:
            self._registry[key].append(handler_factory)
        elif is_command or is_event:
            self._registry[key] = [handler_factory]
318826
void registerMBean(Configuration conf) {
    // We wrap to bypass standard mbean naming convention.
    // This wraping can be removed in java 6 as it is more flexible in
    // package naming for mbeans and their impl.
    StandardMBean bean;
    try {
      versionBeanName = VersionInfo.registerJMX("NameNode");
      myFSMetrics = new FSNamesystemMetrics(conf, this);
      bean = new StandardMBean(this, FSNamesystemMBean.class);
      mbeanName = MBeanUtil.registerMBean("NameNode", "FSNamesystemState", bean);
    } catch (NotCompliantMBeanException e) {
      e.printStackTrace();
    }

    LOG.info("Registered FSNamesystemStatusMBean");
  }