Path: blob/master/src/java.management/share/classes/java/lang/management/ManagementFactory.java
41159 views
/*1* Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.lang.management;26import java.io.FilePermission;27import java.io.IOException;28import javax.management.DynamicMBean;29import javax.management.MBeanServer;30import javax.management.MBeanServerConnection;31import javax.management.MBeanServerFactory;32import javax.management.MBeanServerPermission;33import javax.management.NotificationEmitter;34import javax.management.ObjectName;35import javax.management.InstanceNotFoundException;36import javax.management.MalformedObjectNameException;37import javax.management.StandardEmitterMBean;38import javax.management.StandardMBean;39import java.security.AccessController;40import java.security.Permission;41import java.security.PrivilegedAction;42import java.security.PrivilegedActionException;43import java.security.PrivilegedExceptionAction;44import java.util.ArrayList;45import java.util.Collection;46import java.util.Collections;47import java.util.HashMap;48import java.util.HashSet;49import java.util.List;50import java.util.Map;51import java.util.Optional;52import java.util.ServiceLoader;53import java.util.Set;54import java.util.stream.Collectors;55import java.util.stream.Stream;56import javax.management.JMX;57import sun.management.Util;58import sun.management.spi.PlatformMBeanProvider;59import sun.management.spi.PlatformMBeanProvider.PlatformComponent;6061/**62* The {@code ManagementFactory} class is a factory class for getting63* managed beans for the Java platform.64* This class consists of static methods each of which returns65* one or more <i>platform MXBeans</i> representing66* the management interface of a component of the Java virtual67* machine.68*69* <h2><a id="MXBean">Platform MXBeans</a></h2>70* <p>71* A platform MXBean is a <i>managed bean</i> that72* conforms to the <a href="../../../javax/management/package-summary.html">JMX</a>73* Instrumentation Specification and only uses a set of basic data types.74* A JMX management application and the {@linkplain75* #getPlatformMBeanServer platform MBeanServer}76* can interoperate without requiring classes for MXBean specific77* data types.78* The data types being transmitted between the JMX connector79* server and the connector client are80* {@linkplain javax.management.openmbean.OpenType open types}81* and this allows interoperation across versions.82* See <a href="../../../javax/management/MXBean.html#MXBean-spec">83* the specification of MXBeans</a> for details.84*85* <a id="MXBeanNames"></a>86* <p>Each platform MXBean is a {@link PlatformManagedObject}87* and it has a unique88* {@link javax.management.ObjectName ObjectName} for89* registration in the platform {@code MBeanServer} as returned by90* by the {@link PlatformManagedObject#getObjectName getObjectName}91* method.92*93* <p>94* An application can access a platform MXBean in the following ways:95* <h3>1. Direct access to an MXBean interface</h3>96* <blockquote>97* <ul>98* <li>Get an MXBean instance by calling the99* {@link #getPlatformMXBean(Class) getPlatformMXBean} or100* {@link #getPlatformMXBeans(Class) getPlatformMXBeans} method101* and access the MXBean locally in the running102* virtual machine.103* </li>104* <li>Construct an MXBean proxy instance that forwards the105* method calls to a given {@link MBeanServer MBeanServer} by calling106* the {@link #getPlatformMXBean(MBeanServerConnection, Class)} or107* {@link #getPlatformMXBeans(MBeanServerConnection, Class)} method.108* The {@link #newPlatformMXBeanProxy newPlatformMXBeanProxy} method109* can also be used to construct an MXBean proxy instance of110* a given {@code ObjectName}.111* A proxy is typically constructed to remotely access112* an MXBean of another running virtual machine.113* </li>114* </ul>115* <h3>2. Indirect access to an MXBean interface via MBeanServer</h3>116* <ul>117* <li>Go through the platform {@code MBeanServer} to access MXBeans118* locally or a specific {@code MBeanServerConnection} to access119* MXBeans remotely.120* The attributes and operations of an MXBean use only121* <em>JMX open types</em> which include basic data types,122* {@link javax.management.openmbean.CompositeData CompositeData},123* and {@link javax.management.openmbean.TabularData TabularData}124* defined in125* {@link javax.management.openmbean.OpenType OpenType}.126* The mapping is specified in127* the {@linkplain javax.management.MXBean MXBean} specification128* for details.129* </li>130* </ul>131* </blockquote>132*133* <p>134* The {@link #getPlatformManagementInterfaces getPlatformManagementInterfaces}135* method returns all management interfaces supported in the Java virtual machine136* including the standard management interfaces listed in the tables137* below as well as the management interfaces extended by the JDK implementation.138* <p>139* A Java virtual machine has a single instance of the following management140* interfaces:141*142* <table class="striped" style="margin-left:2em">143* <caption style="display:none">The list of Management Interfaces and their single instances</caption>144* <thead>145* <tr>146* <th scope="col">Management Interface</th>147* <th scope="col">ObjectName</th>148* </tr>149* </thead>150* <tbody style="text-align:left;">151* <tr>152* <th scope="row"> {@link ClassLoadingMXBean} </th>153* <td> {@link #CLASS_LOADING_MXBEAN_NAME154* java.lang:type=ClassLoading}</td>155* </tr>156* <tr>157* <th scope="row"> {@link MemoryMXBean} </th>158* <td> {@link #MEMORY_MXBEAN_NAME159* java.lang:type=Memory}</td>160* </tr>161* <tr>162* <th scope="row"> {@link ThreadMXBean} </th>163* <td> {@link #THREAD_MXBEAN_NAME164* java.lang:type=Threading}</td>165* </tr>166* <tr>167* <th scope="row"> {@link RuntimeMXBean} </th>168* <td> {@link #RUNTIME_MXBEAN_NAME169* java.lang:type=Runtime}</td>170* </tr>171* <tr>172* <th scope="row"> {@link OperatingSystemMXBean} </th>173* <td> {@link #OPERATING_SYSTEM_MXBEAN_NAME174* java.lang:type=OperatingSystem}</td>175* </tr>176* <tr>177* <th scope="row"> {@link PlatformLoggingMXBean} </th>178* <td> {@link java.util.logging.LogManager#LOGGING_MXBEAN_NAME179* java.util.logging:type=Logging}</td>180* </tr>181* </tbody>182* </table>183*184* <p>185* A Java virtual machine has zero or a single instance of186* the following management interfaces.187*188* <table class="striped" style="margin-left:2em">189* <caption style="display:none">The list of Management Interfaces and their single instances</caption>190* <thead>191* <tr>192* <th scope="col">Management Interface</th>193* <th scope="col">ObjectName</th>194* </tr>195* </thead>196* <tbody style="text-align:left;">197* <tr>198* <th scope="row"> {@link CompilationMXBean} </th>199* <td> {@link #COMPILATION_MXBEAN_NAME200* java.lang:type=Compilation}</td>201* </tr>202* </tbody>203* </table>204*205* <p>206* A Java virtual machine may have one or more instances of the following207* management interfaces.208* <table class="striped" style="margin-left:2em">209* <caption style="display:none">The list of Management Interfaces and their single instances</caption>210* <thead>211* <tr>212* <th scope="col">Management Interface</th>213* <th scope="col">ObjectName</th>214* </tr>215* </thead>216* <tbody style="text-align:left;">217* <tr>218* <th scope="row"> {@link GarbageCollectorMXBean} </th>219* <td> {@link #GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE220* java.lang:type=GarbageCollector}{@code ,name=}<i>collector's name</i></td>221* </tr>222* <tr>223* <th scope="row"> {@link MemoryManagerMXBean} </th>224* <td> {@link #MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE225* java.lang:type=MemoryManager}{@code ,name=}<i>manager's name</i></td>226* </tr>227* <tr>228* <th scope="row"> {@link MemoryPoolMXBean} </th>229* <td> {@link #MEMORY_POOL_MXBEAN_DOMAIN_TYPE230* java.lang:type=MemoryPool}{@code ,name=}<i>pool's name</i></td>231* </tr>232* <tr>233* <th scope="row"> {@link BufferPoolMXBean} </th>234* <td> {@code java.nio:type=BufferPool,name=}<i>pool name</i></td>235* </tr>236* </tbody>237* </table>238*239* @see <a href="../../../javax/management/package-summary.html">240* JMX Specification</a>241* @see <a href="package-summary.html#examples">242* Ways to Access Management Metrics</a>243* @see javax.management.MXBean244*245* @author Mandy Chung246* @since 1.5247*/248@SuppressWarnings("removal")249public class ManagementFactory {250// A class with only static fields and methods.251private ManagementFactory() {};252253/**254* String representation of the255* {@code ObjectName} for the {@link ClassLoadingMXBean}.256*/257public static final String CLASS_LOADING_MXBEAN_NAME =258"java.lang:type=ClassLoading";259260/**261* String representation of the262* {@code ObjectName} for the {@link CompilationMXBean}.263*/264public static final String COMPILATION_MXBEAN_NAME =265"java.lang:type=Compilation";266267/**268* String representation of the269* {@code ObjectName} for the {@link MemoryMXBean}.270*/271public static final String MEMORY_MXBEAN_NAME =272"java.lang:type=Memory";273274/**275* String representation of the276* {@code ObjectName} for the {@link OperatingSystemMXBean}.277*/278public static final String OPERATING_SYSTEM_MXBEAN_NAME =279"java.lang:type=OperatingSystem";280281/**282* String representation of the283* {@code ObjectName} for the {@link RuntimeMXBean}.284*/285public static final String RUNTIME_MXBEAN_NAME =286"java.lang:type=Runtime";287288/**289* String representation of the290* {@code ObjectName} for the {@link ThreadMXBean}.291*/292public static final String THREAD_MXBEAN_NAME =293"java.lang:type=Threading";294295/**296* The domain name and the type key property in297* the {@code ObjectName} for a {@link GarbageCollectorMXBean}.298* The unique {@code ObjectName} for a {@code GarbageCollectorMXBean}299* can be formed by appending this string with300* "{@code ,name=}<i>collector's name</i>".301*/302public static final String GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE =303"java.lang:type=GarbageCollector";304305/**306* The domain name and the type key property in307* the {@code ObjectName} for a {@link MemoryManagerMXBean}.308* The unique {@code ObjectName} for a {@code MemoryManagerMXBean}309* can be formed by appending this string with310* "{@code ,name=}<i>manager's name</i>".311*/312public static final String MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE=313"java.lang:type=MemoryManager";314315/**316* The domain name and the type key property in317* the {@code ObjectName} for a {@link MemoryPoolMXBean}.318* The unique {@code ObjectName} for a {@code MemoryPoolMXBean}319* can be formed by appending this string with320* {@code ,name=}<i>pool's name</i>.321*/322public static final String MEMORY_POOL_MXBEAN_DOMAIN_TYPE=323"java.lang:type=MemoryPool";324325/**326* Returns the managed bean for the class loading system of327* the Java virtual machine.328*329* @return a {@link ClassLoadingMXBean} object for330* the Java virtual machine.331*/332public static ClassLoadingMXBean getClassLoadingMXBean() {333return getPlatformMXBean(ClassLoadingMXBean.class);334}335336/**337* Returns the managed bean for the memory system of338* the Java virtual machine.339*340* @return a {@link MemoryMXBean} object for the Java virtual machine.341*/342public static MemoryMXBean getMemoryMXBean() {343return getPlatformMXBean(MemoryMXBean.class);344}345346/**347* Returns the managed bean for the thread system of348* the Java virtual machine.349*350* @return a {@link ThreadMXBean} object for the Java virtual machine.351*/352public static ThreadMXBean getThreadMXBean() {353return getPlatformMXBean(ThreadMXBean.class);354}355356/**357* Returns the managed bean for the runtime system of358* the Java virtual machine.359*360* @return a {@link RuntimeMXBean} object for the Java virtual machine.361362*/363public static RuntimeMXBean getRuntimeMXBean() {364return getPlatformMXBean(RuntimeMXBean.class);365}366367/**368* Returns the managed bean for the compilation system of369* the Java virtual machine. This method returns {@code null}370* if the Java virtual machine has no compilation system.371*372* @return a {@link CompilationMXBean} object for the Java virtual373* machine or {@code null} if the Java virtual machine has374* no compilation system.375*/376public static CompilationMXBean getCompilationMXBean() {377return getPlatformMXBean(CompilationMXBean.class);378}379380/**381* Returns the managed bean for the operating system on which382* the Java virtual machine is running.383*384* @return an {@link OperatingSystemMXBean} object for385* the Java virtual machine.386*/387public static OperatingSystemMXBean getOperatingSystemMXBean() {388return getPlatformMXBean(OperatingSystemMXBean.class);389}390391/**392* Returns a list of {@link MemoryPoolMXBean} objects in the393* Java virtual machine.394* The Java virtual machine can have one or more memory pools.395* It may add or remove memory pools during execution.396*397* @return a list of {@code MemoryPoolMXBean} objects.398*399*/400public static List<MemoryPoolMXBean> getMemoryPoolMXBeans() {401return getPlatformMXBeans(MemoryPoolMXBean.class);402}403404/**405* Returns a list of {@link MemoryManagerMXBean} objects406* in the Java virtual machine.407* The Java virtual machine can have one or more memory managers.408* It may add or remove memory managers during execution.409*410* @return a list of {@code MemoryManagerMXBean} objects.411*412*/413public static List<MemoryManagerMXBean> getMemoryManagerMXBeans() {414return getPlatformMXBeans(MemoryManagerMXBean.class);415}416417418/**419* Returns a list of {@link GarbageCollectorMXBean} objects420* in the Java virtual machine.421* The Java virtual machine may have one or more422* {@code GarbageCollectorMXBean} objects.423* It may add or remove {@code GarbageCollectorMXBean}424* during execution.425*426* @return a list of {@code GarbageCollectorMXBean} objects.427*428*/429public static List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() {430return getPlatformMXBeans(GarbageCollectorMXBean.class);431}432433private static MBeanServer platformMBeanServer;434/**435* Returns the platform {@link javax.management.MBeanServer MBeanServer}.436* On the first call to this method, it first creates the platform437* {@code MBeanServer} by calling the438* {@link javax.management.MBeanServerFactory#createMBeanServer439* MBeanServerFactory.createMBeanServer}440* method and registers each platform MXBean in this platform441* {@code MBeanServer} with its442* {@link PlatformManagedObject#getObjectName ObjectName}.443* This method, in subsequent calls, will simply return the444* initially created platform {@code MBeanServer}.445* <p>446* MXBeans that get created and destroyed dynamically, for example,447* memory {@link MemoryPoolMXBean pools} and448* {@link MemoryManagerMXBean managers},449* will automatically be registered and deregistered into the platform450* {@code MBeanServer}.451* <p>452* If the system property {@code javax.management.builder.initial}453* is set, the platform {@code MBeanServer} creation will be done454* by the specified {@link javax.management.MBeanServerBuilder}.455* <p>456* It is recommended that this platform MBeanServer also be used457* to register other application managed beans458* besides the platform MXBeans.459* This will allow all MBeans to be published through the same460* {@code MBeanServer} and hence allow for easier network publishing461* and discovery.462* Name conflicts with the platform MXBeans should be avoided.463*464* @return the platform {@code MBeanServer}; the platform465* MXBeans are registered into the platform {@code MBeanServer}466* at the first time this method is called.467*468* @throws SecurityException if there is a security manager469* and the caller does not have the permission required by470* {@link javax.management.MBeanServerFactory#createMBeanServer}.471*472* @see javax.management.MBeanServerFactory473* @see javax.management.MBeanServerFactory#createMBeanServer474*/475public static synchronized MBeanServer getPlatformMBeanServer() {476SecurityManager sm = System.getSecurityManager();477if (sm != null) {478Permission perm = new MBeanServerPermission("createMBeanServer");479sm.checkPermission(perm);480}481482if (platformMBeanServer == null) {483platformMBeanServer = MBeanServerFactory.createMBeanServer();484platformComponents()485.stream()486.filter(PlatformComponent::shouldRegister)487.flatMap(pc -> pc.nameToMBeanMap().entrySet().stream())488.forEach(entry -> addMXBean(platformMBeanServer, entry.getKey(), entry.getValue()));489}490return platformMBeanServer;491}492493/**494* Returns a proxy for a platform MXBean interface of a495* given <a href="#MXBeanNames">MXBean name</a>496* that forwards its method calls through the given497* {@code MBeanServerConnection}.498*499* <p>This method is equivalent to:500* <blockquote>501* {@link java.lang.reflect.Proxy#newProxyInstance502* Proxy.newProxyInstance}{@code (mxbeanInterface.getClassLoader(),503* new Class[] { mxbeanInterface }, handler)}504* </blockquote>505*506* where {@code handler} is an {@link java.lang.reflect.InvocationHandler507* InvocationHandler} to which method invocations to the MXBean interface508* are dispatched. This {@code handler} converts an input parameter509* from an MXBean data type to its mapped open type before forwarding510* to the {@code MBeanServer} and converts a return value from511* an MXBean method call through the {@code MBeanServer}512* from an open type to the corresponding return type declared in513* the MXBean interface.514*515* <p>516* If the MXBean is a notification emitter (i.e.,517* it implements518* {@link javax.management.NotificationEmitter NotificationEmitter}),519* both the {@code mxbeanInterface} and {@code NotificationEmitter}520* will be implemented by this proxy.521*522* <p>523* <b>Notes:</b>524* <ol>525* <li>Using an MXBean proxy is a convenience remote access to526* a platform MXBean of a running virtual machine. All method527* calls to the MXBean proxy are forwarded to an528* {@code MBeanServerConnection} where529* {@link java.io.IOException IOException} may be thrown530* when the communication problem occurs with the connector server.531* If thrown, {@link java.io.IOException IOException} will be wrappped in532* {@link java.lang.reflect.UndeclaredThrowableException UndeclaredThrowableException}.533* An application remotely accessing the platform MXBeans using534* proxy should prepare to catch {@code UndeclaredThrowableException} and535* handle its {@linkplain java.lang.reflect.UndeclaredThrowableException#getCause() cause}536* as if that cause had been thrown by the {@code MBeanServerConnection}537* interface.</li>538*539* <li>When a client application is designed to remotely access MXBeans540* for a running virtual machine whose version is different than541* the version on which the application is running,542* it should prepare to catch543* {@link java.io.InvalidObjectException InvalidObjectException}544* which is thrown when an MXBean proxy receives a name of an545* enum constant which is missing in the enum class loaded in546* the client application. If thrown,547* {@link java.io.InvalidObjectException InvalidObjectException} will be548* wrappped in549* {@link java.lang.reflect.UndeclaredThrowableException UndeclaredThrowableException}.550* </li>551*552* <li>{@link javax.management.MBeanServerInvocationHandler553* MBeanServerInvocationHandler} or its554* {@link javax.management.MBeanServerInvocationHandler#newProxyInstance555* newProxyInstance} method cannot be used to create556* a proxy for a platform MXBean. The proxy object created557* by {@code MBeanServerInvocationHandler} does not handle558* the properties of the platform MXBeans described in559* the <a href="#MXBean">class specification</a>.560*</li>561* </ol>562*563* @param connection the {@code MBeanServerConnection} to forward to.564* @param mxbeanName the name of a platform MXBean within565* {@code connection} to forward to. {@code mxbeanName} must be566* in the format of {@link ObjectName ObjectName}.567* @param mxbeanInterface the MXBean interface to be implemented568* by the proxy.569* @param <T> an {@code mxbeanInterface} type parameter570*571* @return a proxy for a platform MXBean interface of a572* given <a href="#MXBeanNames">MXBean name</a>573* that forwards its method calls through the given574* {@code MBeanServerConnection}, or {@code null} if not exist.575*576* @throws IllegalArgumentException if577* <ul>578* <li>{@code mxbeanName} is not with a valid579* {@link ObjectName ObjectName} format, or</li>580* <li>the named MXBean in the {@code connection} is581* not a MXBean provided by the platform, or</li>582* <li>the named MXBean is not registered in the583* {@code MBeanServerConnection}, or</li>584* <li>the named MXBean is not an instance of the given585* {@code mxbeanInterface}</li>586* </ul>587*588* @throws java.io.IOException if a communication problem589* occurred when accessing the {@code MBeanServerConnection}.590*/591public static <T> T592newPlatformMXBeanProxy(MBeanServerConnection connection,593String mxbeanName,594Class<T> mxbeanInterface)595throws java.io.IOException {596597// Only allow MXBean interfaces from the platform modules loaded by the598// bootstrap or platform class loader599final Class<?> cls = mxbeanInterface;600ClassLoader loader =601AccessController.doPrivileged(602(PrivilegedAction<ClassLoader>) () -> cls.getClassLoader());603if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) {604throw new IllegalArgumentException(mxbeanName +605" is not a platform MXBean");606}607608try {609final ObjectName objName = new ObjectName(mxbeanName);610String intfName = mxbeanInterface.getName();611if (!isInstanceOf(connection, objName, intfName)) {612throw new IllegalArgumentException(mxbeanName +613" is not an instance of " + mxbeanInterface);614}615616// check if the registered MBean is a notification emitter617boolean emitter = connection.isInstanceOf(objName, NOTIF_EMITTER);618619// create an MXBean proxy620return JMX.newMXBeanProxy(connection, objName, mxbeanInterface,621emitter);622} catch (InstanceNotFoundException|MalformedObjectNameException e) {623throw new IllegalArgumentException(e);624}625}626627// This makes it possible to obtain an instance of LoggingMXBean628// using newPlatformMXBeanProxy(mbs, on, LoggingMXBean.class)629// even though the underlying MXBean no longer implements630// java.util.logging.LoggingMXBean.631// Altough java.util.logging.LoggingMXBean is deprecated, an application632// that uses newPlatformMXBeanProxy(mbs, on, LoggingMXBean.class) will633// continue to work.634//635private static boolean isInstanceOf(MBeanServerConnection connection,636ObjectName objName, String intfName)637throws InstanceNotFoundException, IOException638{639// special case for java.util.logging.LoggingMXBean.640// java.util.logging.LoggingMXBean is deprecated and641// replaced with java.lang.management.PlatformLoggingMXBean,642// so we will consider that any MBean implementing643// java.lang.management.PlatformLoggingMXBean also implements644// java.util.logging.LoggingMXBean.645if ("java.util.logging.LoggingMXBean".equals(intfName)) {646if (connection.isInstanceOf(objName,647PlatformLoggingMXBean.class.getName())) {648return true;649}650}651return connection.isInstanceOf(objName, intfName);652}653654/**655* Returns the platform MXBean implementing656* the given {@code mxbeanInterface} which is specified657* to have one single instance in the Java virtual machine.658* This method may return {@code null} if the management interface659* is not implemented in the Java virtual machine (for example,660* a Java virtual machine with no compilation system does not661* implement {@link CompilationMXBean});662* otherwise, this method is equivalent to calling:663* <pre>664* {@link #getPlatformMXBeans(Class)665* getPlatformMXBeans(mxbeanInterface)}.get(0);666* </pre>667*668* @param mxbeanInterface a management interface for a platform669* MXBean with one single instance in the Java virtual machine670* if implemented.671* @param <T> an {@code mxbeanInterface} type parameter672*673* @return the platform MXBean that implements674* {@code mxbeanInterface}, or {@code null} if not exist.675*676* @throws IllegalArgumentException if {@code mxbeanInterface}677* is not a platform management interface or678* not a singleton platform MXBean.679*680* @since 1.7681*/682public static <T extends PlatformManagedObject>683T getPlatformMXBean(Class<T> mxbeanInterface) {684PlatformComponent<?> pc = PlatformMBeanFinder.findSingleton(mxbeanInterface);685686List<? extends T> mbeans = pc.getMBeans(mxbeanInterface);687assert mbeans.isEmpty() || mbeans.size() == 1;688return mbeans.isEmpty() ? null : mbeans.get(0);689}690691/**692* Returns the list of platform MXBeans implementing693* the given {@code mxbeanInterface} in the Java694* virtual machine.695* The returned list may contain zero, one, or more instances.696* The number of instances in the returned list is defined697* in the specification of the given management interface.698* The order is undefined and there is no guarantee that699* the list returned is in the same order as previous invocations.700*701* @param mxbeanInterface a management interface for a platform702* MXBean703* @param <T> an {@code mxbeanInterface} type parameter704*705* @return the list of platform MXBeans that implement706* {@code mxbeanInterface}.707*708* @throws IllegalArgumentException if {@code mxbeanInterface}709* is not a platform management interface.710*711* @since 1.7712*/713public static <T extends PlatformManagedObject> List<T>714getPlatformMXBeans(Class<T> mxbeanInterface) {715// Validates at first the specified interface by finding at least one716// PlatformComponent whose MXBean implements this interface.717// An interface can be implemented by different MBeans, provided by718// different platform components.719PlatformComponent<?> pc = PlatformMBeanFinder.findFirst(mxbeanInterface);720if (pc == null) {721throw new IllegalArgumentException(mxbeanInterface.getName()722+ " is not a platform management interface");723}724725return platformComponents().stream()726.flatMap(p -> p.getMBeans(mxbeanInterface).stream())727.collect(Collectors.toList());728}729730/**731* Returns the platform MXBean proxy for732* {@code mxbeanInterface} which is specified to have one single733* instance in a Java virtual machine and the proxy will734* forward the method calls through the given {@code MBeanServerConnection}.735* This method may return {@code null} if the management interface736* is not implemented in the Java virtual machine being monitored737* (for example, a Java virtual machine with no compilation system738* does not implement {@link CompilationMXBean});739* otherwise, this method is equivalent to calling:740* <pre>741* {@link #getPlatformMXBeans(MBeanServerConnection, Class)742* getPlatformMXBeans(connection, mxbeanInterface)}.get(0);743* </pre>744*745* @param connection the {@code MBeanServerConnection} to forward to.746* @param mxbeanInterface a management interface for a platform747* MXBean with one single instance in the Java virtual machine748* being monitored, if implemented.749* @param <T> an {@code mxbeanInterface} type parameter750*751* @return the platform MXBean proxy for752* forwarding the method calls of the {@code mxbeanInterface}753* through the given {@code MBeanServerConnection},754* or {@code null} if not exist.755*756* @throws IllegalArgumentException if {@code mxbeanInterface}757* is not a platform management interface or758* not a singleton platform MXBean.759* @throws java.io.IOException if a communication problem760* occurred when accessing the {@code MBeanServerConnection}.761*762* @see #newPlatformMXBeanProxy763* @since 1.7764*/765public static <T extends PlatformManagedObject>766T getPlatformMXBean(MBeanServerConnection connection,767Class<T> mxbeanInterface)768throws java.io.IOException769{770PlatformComponent<?> pc = PlatformMBeanFinder.findSingleton(mxbeanInterface);771return newPlatformMXBeanProxy(connection, pc.getObjectNamePattern(), mxbeanInterface);772}773774/**775* Returns the list of the platform MXBean proxies for776* forwarding the method calls of the {@code mxbeanInterface}777* through the given {@code MBeanServerConnection}.778* The returned list may contain zero, one, or more instances.779* The number of instances in the returned list is defined780* in the specification of the given management interface.781* The order is undefined and there is no guarantee that782* the list returned is in the same order as previous invocations.783*784* @param connection the {@code MBeanServerConnection} to forward to.785* @param mxbeanInterface a management interface for a platform786* MXBean787* @param <T> an {@code mxbeanInterface} type parameter788*789* @return the list of platform MXBean proxies for790* forwarding the method calls of the {@code mxbeanInterface}791* through the given {@code MBeanServerConnection}.792*793* @throws IllegalArgumentException if {@code mxbeanInterface}794* is not a platform management interface.795*796* @throws java.io.IOException if a communication problem797* occurred when accessing the {@code MBeanServerConnection}.798*799* @see #newPlatformMXBeanProxy800* @since 1.7801*/802public static <T extends PlatformManagedObject>803List<T> getPlatformMXBeans(MBeanServerConnection connection,804Class<T> mxbeanInterface)805throws java.io.IOException806{807// Validates at first the specified interface by finding at least one808// PlatformComponent whose MXBean implements this interface.809// An interface can be implemented by different MBeans, provided by810// different platform components.811PlatformComponent<?> pc = PlatformMBeanFinder.findFirst(mxbeanInterface);812if (pc == null) {813throw new IllegalArgumentException(mxbeanInterface.getName()814+ " is not a platform management interface");815}816817// Collect all names, eliminate duplicates.818Stream<String> names = Stream.empty();819for (PlatformComponent<?> p : platformComponents()) {820names = Stream.concat(names, getProxyNames(p, connection, mxbeanInterface));821}822Set<String> objectNames = names.collect(Collectors.toSet());823if (objectNames.isEmpty()) return Collections.emptyList();824825// Map names on proxies.826List<T> proxies = new ArrayList<>();827for (String name : objectNames) {828proxies.add(newPlatformMXBeanProxy(connection, name, mxbeanInterface));829}830return proxies;831}832833// Returns a stream containing all ObjectNames of the MBeans represented by834// the specified PlatformComponent and implementing the specified interface.835// If the PlatformComponent is a singleton, the name returned by836// PlatformComponent.getObjectNamePattern() will be used, otherwise837// we will query the specified MBeanServerConnection (conn.queryNames)838// with the pattern returned by PlatformComponent.getObjectNamePattern()839// in order to find the names of matching MBeans.840// In case of singleton, we do not check whether the MBean is registered841// in the connection because the caller "getPlatformMXBeans" will do the check842// when creating a proxy.843private static Stream<String> getProxyNames(PlatformComponent<?> pc,844MBeanServerConnection conn,845Class<?> intf)846throws IOException847{848if (pc.mbeanInterfaceNames().contains(intf.getName())) {849if (pc.isSingleton()) {850return Stream.of(pc.getObjectNamePattern());851} else {852return conn.queryNames(Util.newObjectName(pc.getObjectNamePattern()), null)853.stream().map(ObjectName::getCanonicalName);854}855}856return Stream.empty();857}858859/**860* Returns the set of {@code Class} objects, subinterface of861* {@link PlatformManagedObject}, representing862* all management interfaces for863* monitoring and managing the Java platform.864*865* @return the set of {@code Class} objects, subinterface of866* {@link PlatformManagedObject} representing867* the management interfaces for868* monitoring and managing the Java platform.869*870* @since 1.7871*/872public static Set<Class<? extends PlatformManagedObject>>873getPlatformManagementInterfaces()874{875// local variable required here; see JDK-8223553876Stream<Class<? extends PlatformManagedObject>> pmos = platformComponents()877.stream()878.flatMap(pc -> pc.mbeanInterfaces().stream())879.filter(clazz -> PlatformManagedObject.class.isAssignableFrom(clazz))880.map(clazz -> clazz.asSubclass(PlatformManagedObject.class));881return pmos.collect(Collectors.toSet());882}883884private static final String NOTIF_EMITTER =885"javax.management.NotificationEmitter";886887private static void addMXBean(final MBeanServer mbs, String name, final Object pmo)888{889try {890ObjectName oname = ObjectName.getInstance(name);891// Make DynamicMBean out of MXBean by wrapping it with a StandardMBean892AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {893final DynamicMBean dmbean;894if (pmo instanceof DynamicMBean) {895dmbean = DynamicMBean.class.cast(pmo);896} else if (pmo instanceof NotificationEmitter) {897dmbean = new StandardEmitterMBean(pmo, null, true, (NotificationEmitter) pmo);898} else {899dmbean = new StandardMBean(pmo, null, true);900}901902mbs.registerMBean(dmbean, oname);903return null;904});905} catch (MalformedObjectNameException mone) {906throw new IllegalArgumentException(mone);907} catch (PrivilegedActionException e) {908throw new RuntimeException(e.getException());909}910}911912private static Collection<PlatformComponent<?>> platformComponents()913{914return PlatformMBeanFinder.getMap().values();915}916917private static class PlatformMBeanFinder {918private static final Map<String, PlatformComponent<?>> componentMap;919920static {921// get all providers922List<PlatformMBeanProvider> providers = AccessController.doPrivileged(923new PrivilegedAction<List<PlatformMBeanProvider>>() {924@Override925public List<PlatformMBeanProvider> run() {926List<PlatformMBeanProvider> all = new ArrayList<>();927for (PlatformMBeanProvider provider : ServiceLoader.loadInstalled(PlatformMBeanProvider.class)) {928all.add(provider);929}930all.add(new DefaultPlatformMBeanProvider());931return all;932}933}, null, new FilePermission("<<ALL FILES>>", "read"),934new RuntimePermission("sun.management.spi.PlatformMBeanProvider.subclass"));935936// load all platform components into a map937var map = new HashMap<String, PlatformComponent<?>>();938for (PlatformMBeanProvider provider : providers) {939// For each provider, ensure that two different components are not declared940// with the same object name pattern.941var names = new HashSet<String>();942for (PlatformComponent<?> component : provider.getPlatformComponentList()) {943String name = component.getObjectNamePattern();944if (!names.add(name)) {945throw new InternalError(name +946" has been used as key by this provider" +947", it cannot be reused for " + component);948}949// The first one wins if multiple PlatformComponents defined by950// different providers use the same ObjectName pattern951map.putIfAbsent(name, component);952}953}954componentMap = map;955}956957static Map<String, PlatformComponent<?>> getMap() {958return componentMap;959}960961// Finds the first PlatformComponent whose mbeanInterfaceNames() list962// contains the specified class name. An MBean interface can be implemented963// by different MBeans, provided by different platform components.964// For instance the MemoryManagerMXBean interface is implemented both by965// regular memory managers, and garbage collector MXBeans. This method is966// mainly used to verify that there is at least one PlatformComponent967// which provides an implementation of the desired interface.968static PlatformComponent<?> findFirst(Class<?> mbeanIntf)969{970String name = mbeanIntf.getName();971Optional<PlatformComponent<?>> op = getMap().values()972.stream()973.filter(pc -> pc.mbeanInterfaceNames().contains(name))974.findFirst();975976if (op.isPresent()) {977return op.get();978} else {979return null;980}981}982983// Finds a PlatformComponent whose mbeanInterface name list contains984// the specified class name, and make sure that one and only one exists.985static PlatformComponent<?> findSingleton(Class<?> mbeanIntf)986{987String name = mbeanIntf.getName();988Optional<PlatformComponent<?>> op = getMap().values()989.stream()990.filter(pc -> pc.mbeanInterfaceNames().contains(name))991.reduce((p1, p2) -> {992if (p2 != null) {993throw new IllegalArgumentException(mbeanIntf.getName() +994" can have more than one instance");995} else {996return p1;997}998});9991000PlatformComponent<?> singleton = op.isPresent() ? op.get() : null;1001if (singleton == null) {1002throw new IllegalArgumentException(mbeanIntf.getName() +1003" is not a platform management interface");1004}1005if (!singleton.isSingleton()) {1006throw new IllegalArgumentException(mbeanIntf.getName() +1007" can have more than one instance");1008}1009return singleton;1010}1011}10121013static {1014AccessController.doPrivileged((PrivilegedAction<Void>) () -> {1015System.loadLibrary("management");1016return null;1017});1018}1019}102010211022