3737import javax .annotation .PostConstruct ;
3838import javax .annotation .PreDestroy ;
3939import javax .management .JMException ;
40+ import javax .management .MalformedObjectNameException ;
4041import javax .management .ObjectName ;
4142import java .lang .management .ManagementFactory ;
4243import java .time .Duration ;
5657@ Value .Immutable
5758abstract class _DefaultConnectionContext implements ConnectionContext {
5859
60+ private static final int DEFAULT_PORT = 443 ;
61+
5962 private static final int RECEIVE_BUFFER_SIZE = 10 * 1024 * 1024 ;
6063
6164 private static final int SEND_BUFFER_SIZE = 10 * 1024 * 1024 ;
@@ -69,6 +72,16 @@ abstract class _DefaultConnectionContext implements ConnectionContext {
6972 public final void dispose () {
7073 getConnectionPool ().ifPresent (PoolResources ::dispose );
7174 getThreadPool ().dispose ();
75+
76+ try {
77+ ObjectName name = getByteBufAllocatorObjectName ();
78+
79+ if (ManagementFactory .getPlatformMBeanServer ().isRegistered (name )) {
80+ ManagementFactory .getPlatformMBeanServer ().unregisterMBean (name );
81+ }
82+ } catch (JMException e ) {
83+ this .logger .error ("Unable to register ByteBufAllocator MBean" , e );
84+ }
7285 }
7386
7487 @ Override
@@ -149,7 +162,6 @@ public Mono<Void> trust(String host, int port) {
149162 /**
150163 * The hostname of the API root. Typically something like {@code api.run.pivotal.io}.
151164 */
152- @ Nullable
153165 abstract String getApiHost ();
154166
155167 /**
@@ -225,11 +237,21 @@ LoopResources getThreadPool() {
225237 @ PostConstruct
226238 void monitorByteBufAllocator () {
227239 try {
228- ManagementFactory .getPlatformMBeanServer ()
229- .registerMBean (new ByteBufAllocatorMetricProviderWrapper (PooledByteBufAllocator .DEFAULT ), ObjectName .getInstance ("org.cloudfoundry.reactor:type=ByteBufAllocator" ));
240+ ObjectName name = getByteBufAllocatorObjectName ();
241+
242+ if (ManagementFactory .getPlatformMBeanServer ().isRegistered (name )) {
243+ this .logger .warn ("MBean '{}' is already registered and will be removed. You should only have a single DefaultConnectionContext per endpoint." , name );
244+ ManagementFactory .getPlatformMBeanServer ().unregisterMBean (name );
245+ }
246+
247+ ManagementFactory .getPlatformMBeanServer ().registerMBean (new ByteBufAllocatorMetricProviderWrapper (PooledByteBufAllocator .DEFAULT ), name );
230248 } catch (JMException e ) {
231249 this .logger .error ("Unable to register ByteBufAllocator MBean" , e );
232250 }
233251 }
234252
253+ private ObjectName getByteBufAllocatorObjectName () throws MalformedObjectNameException {
254+ return ObjectName .getInstance (String .format ("org.cloudfoundry.reactor:type=ByteBufAllocator,endpoint=%s/%d" , getApiHost (), getPort ().orElse (DEFAULT_PORT )));
255+ }
256+
235257}
0 commit comments