3838import javax .annotation .PostConstruct ;
3939import javax .annotation .PreDestroy ;
4040import javax .management .JMException ;
41+ import javax .management .MalformedObjectNameException ;
4142import javax .management .ObjectName ;
4243import java .lang .management .ManagementFactory ;
4344import java .time .Duration ;
5758@ Value .Immutable
5859abstract class _DefaultConnectionContext implements ConnectionContext {
5960
61+ private static final int DEFAULT_PORT = 443 ;
62+
6063 private static final int RECEIVE_BUFFER_SIZE = 10 * 1024 * 1024 ;
6164
6265 private static final int SEND_BUFFER_SIZE = 10 * 1024 * 1024 ;
@@ -70,6 +73,16 @@ abstract class _DefaultConnectionContext implements ConnectionContext {
7073 public final void dispose () {
7174 getConnectionPool ().ifPresent (PoolResources ::dispose );
7275 getThreadPool ().dispose ();
76+
77+ try {
78+ ObjectName name = getByteBufAllocatorObjectName ();
79+
80+ if (ManagementFactory .getPlatformMBeanServer ().isRegistered (name )) {
81+ ManagementFactory .getPlatformMBeanServer ().unregisterMBean (name );
82+ }
83+ } catch (JMException e ) {
84+ this .logger .error ("Unable to register ByteBufAllocator MBean" , e );
85+ }
7386 }
7487
7588 /**
@@ -146,7 +159,6 @@ public Mono<Void> trust(String host, int port) {
146159 /**
147160 * The hostname of the API root. Typically something like {@code api.run.pivotal.io}.
148161 */
149- @ Nullable
150162 abstract String getApiHost ();
151163
152164 /**
@@ -222,11 +234,21 @@ LoopResources getThreadPool() {
222234 @ PostConstruct
223235 void monitorByteBufAllocator () {
224236 try {
225- ManagementFactory .getPlatformMBeanServer ()
226- .registerMBean (new ByteBufAllocatorMetricProviderWrapper (PooledByteBufAllocator .DEFAULT ), ObjectName .getInstance ("org.cloudfoundry.reactor:type=ByteBufAllocator" ));
237+ ObjectName name = getByteBufAllocatorObjectName ();
238+
239+ if (ManagementFactory .getPlatformMBeanServer ().isRegistered (name )) {
240+ this .logger .warn ("MBean '{}' is already registered and will be removed. You should only have a single DefaultConnectionContext per endpoint." , name );
241+ ManagementFactory .getPlatformMBeanServer ().unregisterMBean (name );
242+ }
243+
244+ ManagementFactory .getPlatformMBeanServer ().registerMBean (new ByteBufAllocatorMetricProviderWrapper (PooledByteBufAllocator .DEFAULT ), name );
227245 } catch (JMException e ) {
228246 this .logger .error ("Unable to register ByteBufAllocator MBean" , e );
229247 }
230248 }
231249
250+ private ObjectName getByteBufAllocatorObjectName () throws MalformedObjectNameException {
251+ return ObjectName .getInstance (String .format ("org.cloudfoundry.reactor:type=ByteBufAllocator,endpoint=%s/%d" , getApiHost (), getPort ().orElse (DEFAULT_PORT )));
252+ }
253+
232254}
0 commit comments