feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,93 @@
/*
* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
/**
* The management interface for a buffer pool, for example a pool of
* {@link java.nio.ByteBuffer#allocateDirect direct} or {@link
* java.nio.MappedByteBuffer mapped} buffers.
*
* <p> A class implementing this interface is an
* {@link javax.management.MXBean}. A Java
* virtual machine has one or more implementations of this interface. The {@link
* java.lang.management.ManagementFactory#getPlatformMXBeans getPlatformMXBeans}
* method can be used to obtain the list of {@code BufferPoolMXBean} objects
* representing the management interfaces for pools of buffers as follows:
* <pre>
* List&lt;BufferPoolMXBean&gt; pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
* </pre>
*
* <p> The management interfaces are also registered with the platform {@link
* javax.management.MBeanServer MBeanServer}. The {@link
* javax.management.ObjectName ObjectName} that uniquely identifies the
* management interface within the {@code MBeanServer} takes the form:
* <pre>
* java.nio:type=BufferPool,name=<i>pool name</i>
* </pre>
* where <em>pool name</em> is the {@link #getName name} of the buffer pool.
*
* @since 1.7
*/
public interface BufferPoolMXBean extends PlatformManagedObject {
/**
* Returns the name representing this buffer pool.
*
* @return The name of this buffer pool.
*/
String getName();
/**
* Returns an estimate of the number of buffers in the pool.
*
* @return An estimate of the number of buffers in this pool
*/
long getCount();
/**
* Returns an estimate of the total capacity of the buffers in this pool.
* A buffer's capacity is the number of elements it contains and the value
* returned by this method is an estimate of the total capacity of buffers
* in the pool in bytes.
*
* @return An estimate of the total capacity of the buffers in this pool
* in bytes
*/
long getTotalCapacity();
/**
* Returns an estimate of the memory that the Java virtual machine is using
* for this buffer pool. The value returned by this method may differ
* from the estimate of the total {@link #getTotalCapacity capacity} of
* the buffers in this pool. This difference is explained by alignment,
* memory allocator, and other implementation specific reasons.
*
* @return An estimate of the memory that the Java virtual machine is using
* for this buffer pool in bytes, or {@code -1L} if an estimate of
* the memory usage is not available
*/
long getMemoryUsed();
}

View File

@@ -0,0 +1,114 @@
/*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
/**
* The management interface for the class loading system of
* the Java virtual machine.
*
* <p> A Java virtual machine has a single instance of the implementation
* class of this interface. This instance implementing this interface is
* an <a href="ManagementFactory.html#MXBean">MXBean</a>
* that can be obtained by calling
* the {@link ManagementFactory#getClassLoadingMXBean} method or
* from the {@link ManagementFactory#getPlatformMBeanServer
* platform <tt>MBeanServer</tt>}.
*
* <p>The <tt>ObjectName</tt> for uniquely identifying the MXBean for
* the class loading system within an <tt>MBeanServer</tt> is:
* <blockquote>
* {@link ManagementFactory#CLASS_LOADING_MXBEAN_NAME
* <tt>java.lang:type=ClassLoading</tt>}
* </blockquote>
*
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a>
* @see <a href="package-summary.html#examples">
* Ways to Access MXBeans</a>
*
* @author Mandy Chung
* @since 1.5
*/
public interface ClassLoadingMXBean extends PlatformManagedObject {
/**
* Returns the total number of classes that have been loaded since
* the Java virtual machine has started execution.
*
* @return the total number of classes loaded.
*
*/
public long getTotalLoadedClassCount();
/**
* Returns the number of classes that are currently loaded in the
* Java virtual machine.
*
* @return the number of currently loaded classes.
*/
public int getLoadedClassCount();
/**
* Returns the total number of classes unloaded since the Java virtual machine
* has started execution.
*
* @return the total number of unloaded classes.
*/
public long getUnloadedClassCount();
/**
* Tests if the verbose output for the class loading system is enabled.
*
* @return <tt>true</tt> if the verbose output for the class loading
* system is enabled; <tt>false</tt> otherwise.
*/
public boolean isVerbose();
/**
* Enables or disables the verbose output for the class loading
* system. The verbose output information and the output stream
* to which the verbose information is emitted are implementation
* dependent. Typically, a Java virtual machine implementation
* prints a message each time a class file is loaded.
*
* <p>This method can be called by multiple threads concurrently.
* Each invocation of this method enables or disables the verbose
* output globally.
*
* @param value <tt>true</tt> to enable the verbose output;
* <tt>false</tt> to disable.
*
* @exception java.lang.SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("control").
*/
public void setVerbose(boolean value);
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
/**
* The management interface for the compilation system of
* the Java virtual machine.
*
* <p> A Java virtual machine has a single instance of the implementation
* class of this interface. This instance implementing this interface is
* an <a href="ManagementFactory.html#MXBean">MXBean</a>
* that can be obtained by calling
* the {@link ManagementFactory#getCompilationMXBean} method or
* from the {@link ManagementFactory#getPlatformMBeanServer
* platform <tt>MBeanServer</tt>} method.
*
* <p>The <tt>ObjectName</tt> for uniquely identifying the MXBean for
* the compilation system within an MBeanServer is:
* <blockquote>
* {@link ManagementFactory#COMPILATION_MXBEAN_NAME
* <tt>java.lang:type=Compilation</tt>}
* </blockquote>
*
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a>
* @see <a href="package-summary.html#examples">
* Ways to Access MXBeans</a>
*
* @author Mandy Chung
* @since 1.5
*/
public interface CompilationMXBean extends PlatformManagedObject {
/**
* Returns the name of the Just-in-time (JIT) compiler.
*
* @return the name of the JIT compiler.
*/
public java.lang.String getName();
/**
* Tests if the Java virtual machine supports the monitoring of
* compilation time.
*
* @return <tt>true</tt> if the monitoring of compilation time is
* supported ; <tt>false</tt> otherwise.
*/
public boolean isCompilationTimeMonitoringSupported();
/**
* Returns the approximate accumulated elapsed time (in milliseconds)
* spent in compilation.
* If multiple threads are used for compilation, this value is
* summation of the approximate time that each thread spent in compilation.
*
* <p>This method is optionally supported by the platform.
* A Java virtual machine implementation may not support the compilation
* time monitoring. The {@link #isCompilationTimeMonitoringSupported}
* method can be used to determine if the Java virtual machine
* supports this operation.
*
* <p> This value does not indicate the level of performance of
* the Java virtual machine and is not intended for performance comparisons
* of different virtual machine implementations.
* The implementations may have different definitions and different
* measurements of the compilation time.
*
* @return Compilation time in milliseconds
* @throws java.lang.UnsupportedOperationException if the Java
* virtual machine does not support
* this operation.
*
*/
public long getTotalCompilationTime();
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
/**
* The management interface for the garbage collection of
* the Java virtual machine. Garbage collection is the process
* that the Java virtual machine uses to find and reclaim unreachable
* objects to free up memory space. A garbage collector is one type of
* {@link MemoryManagerMXBean memory manager}.
*
* <p> A Java virtual machine may have one or more instances of
* the implementation class of this interface.
* An instance implementing this interface is
* an <a href="ManagementFactory.html#MXBean">MXBean</a>
* that can be obtained by calling
* the {@link ManagementFactory#getGarbageCollectorMXBeans} method or
* from the {@link ManagementFactory#getPlatformMBeanServer
* platform <tt>MBeanServer</tt>} method.
*
* <p>The <tt>ObjectName</tt> for uniquely identifying the MXBean for
* a garbage collector within an MBeanServer is:
* <blockquote>
* {@link ManagementFactory#GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE
* <tt>java.lang:type=GarbageCollector</tt>}<tt>,name=</tt><i>collector's name</i>
* </blockquote>
*
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* A platform usually includes additional platform-dependent information
* specific to a garbage collection algorithm for monitoring.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see MemoryMXBean
*
* @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a>
* @see <a href="package-summary.html#examples">
* Ways to Access MXBeans</a>
*
* @author Mandy Chung
* @since 1.5
*/
public interface GarbageCollectorMXBean extends MemoryManagerMXBean {
/**
* Returns the total number of collections that have occurred.
* This method returns <tt>-1</tt> if the collection count is undefined for
* this collector.
*
* @return the total number of collections that have occurred.
*/
public long getCollectionCount();
/**
* Returns the approximate accumulated collection elapsed time
* in milliseconds. This method returns <tt>-1</tt> if the collection
* elapsed time is undefined for this collector.
* <p>
* The Java virtual machine implementation may use a high resolution
* timer to measure the elapsed time. This method may return the
* same value even if the collection count has been incremented
* if the collection elapsed time is very short.
*
* @return the approximate accumulated collection elapsed time
* in milliseconds.
*/
public long getCollectionTime();
}

View File

@@ -0,0 +1,164 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
import javax.management.openmbean.CompositeData;
import java.util.concurrent.locks.*;
import sun.management.LockInfoCompositeData;
/**
* Information about a <em>lock</em>. A lock can be a built-in object monitor,
* an <em>ownable synchronizer</em>, or the {@link Condition Condition}
* object associated with synchronizers.
* <p>
* <a name="OwnableSynchronizer">An ownable synchronizer</a> is
* a synchronizer that may be exclusively owned by a thread and uses
* {@link AbstractOwnableSynchronizer AbstractOwnableSynchronizer}
* (or its subclass) to implement its synchronization property.
* {@link ReentrantLock ReentrantLock} and
* {@link ReentrantReadWriteLock ReentrantReadWriteLock} are
* two examples of ownable synchronizers provided by the platform.
*
* <h3><a name="MappedType">MXBean Mapping</a></h3>
* <tt>LockInfo</tt> is mapped to a {@link CompositeData CompositeData}
* as specified in the {@link #from from} method.
*
* @see java.util.concurrent.locks.AbstractOwnableSynchronizer
* @see java.util.concurrent.locks.Condition
*
* @author Mandy Chung
* @since 1.6
*/
public class LockInfo {
private String className;
private int identityHashCode;
/**
* Constructs a <tt>LockInfo</tt> object.
*
* @param className the fully qualified name of the class of the lock object.
* @param identityHashCode the {@link System#identityHashCode
* identity hash code} of the lock object.
*/
public LockInfo(String className, int identityHashCode) {
if (className == null) {
throw new NullPointerException("Parameter className cannot be null");
}
this.className = className;
this.identityHashCode = identityHashCode;
}
/**
* package-private constructors
*/
LockInfo(Object lock) {
this.className = lock.getClass().getName();
this.identityHashCode = System.identityHashCode(lock);
}
/**
* Returns the fully qualified name of the class of the lock object.
*
* @return the fully qualified name of the class of the lock object.
*/
public String getClassName() {
return className;
}
/**
* Returns the identity hash code of the lock object
* returned from the {@link System#identityHashCode} method.
*
* @return the identity hash code of the lock object.
*/
public int getIdentityHashCode() {
return identityHashCode;
}
/**
* Returns a {@code LockInfo} object represented by the
* given {@code CompositeData}.
* The given {@code CompositeData} must contain the following attributes:
* <blockquote>
* <table border summary="The attributes and the types the given CompositeData contains">
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
* </tr>
* <tr>
* <td>className</td>
* <td><tt>java.lang.String</tt></td>
* </tr>
* <tr>
* <td>identityHashCode</td>
* <td><tt>java.lang.Integer</tt></td>
* </tr>
* </table>
* </blockquote>
*
* @param cd {@code CompositeData} representing a {@code LockInfo}
*
* @throws IllegalArgumentException if {@code cd} does not
* represent a {@code LockInfo} with the attributes described
* above.
* @return a {@code LockInfo} object represented
* by {@code cd} if {@code cd} is not {@code null};
* {@code null} otherwise.
*
* @since 1.8
*/
public static LockInfo from(CompositeData cd) {
if (cd == null) {
return null;
}
if (cd instanceof LockInfoCompositeData) {
return ((LockInfoCompositeData) cd).getLockInfo();
} else {
return LockInfoCompositeData.toLockInfo(cd);
}
}
/**
* Returns a string representation of a lock. The returned
* string representation consists of the name of the class of the
* lock object, the at-sign character `@', and the unsigned
* hexadecimal representation of the <em>identity</em> hash code
* of the object. This method returns a string equals to the value of:
* <blockquote>
* <pre>
* lock.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(lock))
* </pre></blockquote>
* where <tt>lock</tt> is the lock object.
*
* @return the string representation of a lock.
*/
public String toString() {
return className + '@' + Integer.toHexString(identityHashCode);
}
}

View File

@@ -0,0 +1,897 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
import javax.management.DynamicMBean;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerFactory;
import javax.management.MBeanServerPermission;
import javax.management.NotificationEmitter;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MalformedObjectNameException;
import javax.management.MBeanRegistrationException;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardEmitterMBean;
import javax.management.StandardMBean;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.security.AccessController;
import java.security.Permission;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import javax.management.JMX;
import sun.management.ManagementFactoryHelper;
import sun.management.ExtendedPlatformComponent;
/**
* The {@code ManagementFactory} class is a factory class for getting
* managed beans for the Java platform.
* This class consists of static methods each of which returns
* one or more <i>platform MXBeans</i> representing
* the management interface of a component of the Java virtual
* machine.
*
* <h3><a name="MXBean">Platform MXBeans</a></h3>
* <p>
* A platform MXBean is a <i>managed bean</i> that
* conforms to the <a href="../../../javax/management/package-summary.html">JMX</a>
* Instrumentation Specification and only uses a set of basic data types.
* A JMX management application and the {@linkplain
* #getPlatformMBeanServer platform MBeanServer}
* can interoperate without requiring classes for MXBean specific
* data types.
* The data types being transmitted between the JMX connector
* server and the connector client are
* {@linkplain javax.management.openmbean.OpenType open types}
* and this allows interoperation across versions.
* See <a href="../../../javax/management/MXBean.html#MXBean-spec">
* the specification of MXBeans</a> for details.
*
* <a name="MXBeanNames"></a>
* <p>Each platform MXBean is a {@link PlatformManagedObject}
* and it has a unique
* {@link javax.management.ObjectName ObjectName} for
* registration in the platform {@code MBeanServer} as returned by
* by the {@link PlatformManagedObject#getObjectName getObjectName}
* method.
*
* <p>
* An application can access a platform MXBean in the following ways:
* <h4>1. Direct access to an MXBean interface</h4>
* <blockquote>
* <ul>
* <li>Get an MXBean instance by calling the
* {@link #getPlatformMXBean(Class) getPlatformMXBean} or
* {@link #getPlatformMXBeans(Class) getPlatformMXBeans} method
* and access the MXBean locally in the running
* virtual machine.
* </li>
* <li>Construct an MXBean proxy instance that forwards the
* method calls to a given {@link MBeanServer MBeanServer} by calling
* the {@link #getPlatformMXBean(MBeanServerConnection, Class)} or
* {@link #getPlatformMXBeans(MBeanServerConnection, Class)} method.
* The {@link #newPlatformMXBeanProxy newPlatformMXBeanProxy} method
* can also be used to construct an MXBean proxy instance of
* a given {@code ObjectName}.
* A proxy is typically constructed to remotely access
* an MXBean of another running virtual machine.
* </li>
* </ul>
* <h4>2. Indirect access to an MXBean interface via MBeanServer</h4>
* <ul>
* <li>Go through the platform {@code MBeanServer} to access MXBeans
* locally or a specific <tt>MBeanServerConnection</tt> to access
* MXBeans remotely.
* The attributes and operations of an MXBean use only
* <em>JMX open types</em> which include basic data types,
* {@link javax.management.openmbean.CompositeData CompositeData},
* and {@link javax.management.openmbean.TabularData TabularData}
* defined in
* {@link javax.management.openmbean.OpenType OpenType}.
* The mapping is specified in
* the {@linkplain javax.management.MXBean MXBean} specification
* for details.
* </li>
* </ul>
* </blockquote>
*
* <p>
* The {@link #getPlatformManagementInterfaces getPlatformManagementInterfaces}
* method returns all management interfaces supported in the Java virtual machine
* including the standard management interfaces listed in the tables
* below as well as the management interfaces extended by the JDK implementation.
* <p>
* A Java virtual machine has a single instance of the following management
* interfaces:
*
* <blockquote>
* <table border summary="The list of Management Interfaces and their single instances">
* <tr>
* <th>Management Interface</th>
* <th>ObjectName</th>
* </tr>
* <tr>
* <td> {@link ClassLoadingMXBean} </td>
* <td> {@link #CLASS_LOADING_MXBEAN_NAME
* java.lang:type=ClassLoading}</td>
* </tr>
* <tr>
* <td> {@link MemoryMXBean} </td>
* <td> {@link #MEMORY_MXBEAN_NAME
* java.lang:type=Memory}</td>
* </tr>
* <tr>
* <td> {@link ThreadMXBean} </td>
* <td> {@link #THREAD_MXBEAN_NAME
* java.lang:type=Threading}</td>
* </tr>
* <tr>
* <td> {@link RuntimeMXBean} </td>
* <td> {@link #RUNTIME_MXBEAN_NAME
* java.lang:type=Runtime}</td>
* </tr>
* <tr>
* <td> {@link OperatingSystemMXBean} </td>
* <td> {@link #OPERATING_SYSTEM_MXBEAN_NAME
* java.lang:type=OperatingSystem}</td>
* </tr>
* <tr>
* <td> {@link PlatformLoggingMXBean} </td>
* <td> {@link java.util.logging.LogManager#LOGGING_MXBEAN_NAME
* java.util.logging:type=Logging}</td>
* </tr>
* </table>
* </blockquote>
*
* <p>
* A Java virtual machine has zero or a single instance of
* the following management interfaces.
*
* <blockquote>
* <table border summary="The list of Management Interfaces and their single instances">
* <tr>
* <th>Management Interface</th>
* <th>ObjectName</th>
* </tr>
* <tr>
* <td> {@link CompilationMXBean} </td>
* <td> {@link #COMPILATION_MXBEAN_NAME
* java.lang:type=Compilation}</td>
* </tr>
* </table>
* </blockquote>
*
* <p>
* A Java virtual machine may have one or more instances of the following
* management interfaces.
* <blockquote>
* <table border summary="The list of Management Interfaces and their single instances">
* <tr>
* <th>Management Interface</th>
* <th>ObjectName</th>
* </tr>
* <tr>
* <td> {@link GarbageCollectorMXBean} </td>
* <td> {@link #GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE
* java.lang:type=GarbageCollector}<tt>,name=</tt><i>collector's name</i></td>
* </tr>
* <tr>
* <td> {@link MemoryManagerMXBean} </td>
* <td> {@link #MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE
* java.lang:type=MemoryManager}<tt>,name=</tt><i>manager's name</i></td>
* </tr>
* <tr>
* <td> {@link MemoryPoolMXBean} </td>
* <td> {@link #MEMORY_POOL_MXBEAN_DOMAIN_TYPE
* java.lang:type=MemoryPool}<tt>,name=</tt><i>pool's name</i></td>
* </tr>
* <tr>
* <td> {@link BufferPoolMXBean} </td>
* <td> {@code java.nio:type=BufferPool,name=}<i>pool name</i></td>
* </tr>
* </table>
* </blockquote>
*
* @see <a href="../../../javax/management/package-summary.html">
* JMX Specification</a>
* @see <a href="package-summary.html#examples">
* Ways to Access Management Metrics</a>
* @see javax.management.MXBean
*
* @author Mandy Chung
* @since 1.5
*/
public class ManagementFactory {
// A class with only static fields and methods.
private ManagementFactory() {};
/**
* String representation of the
* <tt>ObjectName</tt> for the {@link ClassLoadingMXBean}.
*/
public final static String CLASS_LOADING_MXBEAN_NAME =
"java.lang:type=ClassLoading";
/**
* String representation of the
* <tt>ObjectName</tt> for the {@link CompilationMXBean}.
*/
public final static String COMPILATION_MXBEAN_NAME =
"java.lang:type=Compilation";
/**
* String representation of the
* <tt>ObjectName</tt> for the {@link MemoryMXBean}.
*/
public final static String MEMORY_MXBEAN_NAME =
"java.lang:type=Memory";
/**
* String representation of the
* <tt>ObjectName</tt> for the {@link OperatingSystemMXBean}.
*/
public final static String OPERATING_SYSTEM_MXBEAN_NAME =
"java.lang:type=OperatingSystem";
/**
* String representation of the
* <tt>ObjectName</tt> for the {@link RuntimeMXBean}.
*/
public final static String RUNTIME_MXBEAN_NAME =
"java.lang:type=Runtime";
/**
* String representation of the
* <tt>ObjectName</tt> for the {@link ThreadMXBean}.
*/
public final static String THREAD_MXBEAN_NAME =
"java.lang:type=Threading";
/**
* The domain name and the type key property in
* the <tt>ObjectName</tt> for a {@link GarbageCollectorMXBean}.
* The unique <tt>ObjectName</tt> for a <tt>GarbageCollectorMXBean</tt>
* can be formed by appending this string with
* "<tt>,name=</tt><i>collector's name</i>".
*/
public final static String GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE =
"java.lang:type=GarbageCollector";
/**
* The domain name and the type key property in
* the <tt>ObjectName</tt> for a {@link MemoryManagerMXBean}.
* The unique <tt>ObjectName</tt> for a <tt>MemoryManagerMXBean</tt>
* can be formed by appending this string with
* "<tt>,name=</tt><i>manager's name</i>".
*/
public final static String MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE=
"java.lang:type=MemoryManager";
/**
* The domain name and the type key property in
* the <tt>ObjectName</tt> for a {@link MemoryPoolMXBean}.
* The unique <tt>ObjectName</tt> for a <tt>MemoryPoolMXBean</tt>
* can be formed by appending this string with
* <tt>,name=</tt><i>pool's name</i>.
*/
public final static String MEMORY_POOL_MXBEAN_DOMAIN_TYPE=
"java.lang:type=MemoryPool";
/**
* Returns the managed bean for the class loading system of
* the Java virtual machine.
*
* @return a {@link ClassLoadingMXBean} object for
* the Java virtual machine.
*/
public static ClassLoadingMXBean getClassLoadingMXBean() {
return ManagementFactoryHelper.getClassLoadingMXBean();
}
/**
* Returns the managed bean for the memory system of
* the Java virtual machine.
*
* @return a {@link MemoryMXBean} object for the Java virtual machine.
*/
public static MemoryMXBean getMemoryMXBean() {
return ManagementFactoryHelper.getMemoryMXBean();
}
/**
* Returns the managed bean for the thread system of
* the Java virtual machine.
*
* @return a {@link ThreadMXBean} object for the Java virtual machine.
*/
public static ThreadMXBean getThreadMXBean() {
return ManagementFactoryHelper.getThreadMXBean();
}
/**
* Returns the managed bean for the runtime system of
* the Java virtual machine.
*
* @return a {@link RuntimeMXBean} object for the Java virtual machine.
*/
public static RuntimeMXBean getRuntimeMXBean() {
return ManagementFactoryHelper.getRuntimeMXBean();
}
/**
* Returns the managed bean for the compilation system of
* the Java virtual machine. This method returns <tt>null</tt>
* if the Java virtual machine has no compilation system.
*
* @return a {@link CompilationMXBean} object for the Java virtual
* machine or <tt>null</tt> if the Java virtual machine has
* no compilation system.
*/
public static CompilationMXBean getCompilationMXBean() {
return ManagementFactoryHelper.getCompilationMXBean();
}
/**
* Returns the managed bean for the operating system on which
* the Java virtual machine is running.
*
* @return an {@link OperatingSystemMXBean} object for
* the Java virtual machine.
*/
public static OperatingSystemMXBean getOperatingSystemMXBean() {
return ManagementFactoryHelper.getOperatingSystemMXBean();
}
/**
* Returns a list of {@link MemoryPoolMXBean} objects in the
* Java virtual machine.
* The Java virtual machine can have one or more memory pools.
* It may add or remove memory pools during execution.
*
* @return a list of <tt>MemoryPoolMXBean</tt> objects.
*
*/
public static List<MemoryPoolMXBean> getMemoryPoolMXBeans() {
return ManagementFactoryHelper.getMemoryPoolMXBeans();
}
/**
* Returns a list of {@link MemoryManagerMXBean} objects
* in the Java virtual machine.
* The Java virtual machine can have one or more memory managers.
* It may add or remove memory managers during execution.
*
* @return a list of <tt>MemoryManagerMXBean</tt> objects.
*
*/
public static List<MemoryManagerMXBean> getMemoryManagerMXBeans() {
return ManagementFactoryHelper.getMemoryManagerMXBeans();
}
/**
* Returns a list of {@link GarbageCollectorMXBean} objects
* in the Java virtual machine.
* The Java virtual machine may have one or more
* <tt>GarbageCollectorMXBean</tt> objects.
* It may add or remove <tt>GarbageCollectorMXBean</tt>
* during execution.
*
* @return a list of <tt>GarbageCollectorMXBean</tt> objects.
*
*/
public static List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() {
return ManagementFactoryHelper.getGarbageCollectorMXBeans();
}
private static MBeanServer platformMBeanServer;
/**
* Returns the platform {@link javax.management.MBeanServer MBeanServer}.
* On the first call to this method, it first creates the platform
* {@code MBeanServer} by calling the
* {@link javax.management.MBeanServerFactory#createMBeanServer
* MBeanServerFactory.createMBeanServer}
* method and registers each platform MXBean in this platform
* {@code MBeanServer} with its
* {@link PlatformManagedObject#getObjectName ObjectName}.
* This method, in subsequent calls, will simply return the
* initially created platform {@code MBeanServer}.
* <p>
* MXBeans that get created and destroyed dynamically, for example,
* memory {@link MemoryPoolMXBean pools} and
* {@link MemoryManagerMXBean managers},
* will automatically be registered and deregistered into the platform
* {@code MBeanServer}.
* <p>
* If the system property {@code javax.management.builder.initial}
* is set, the platform {@code MBeanServer} creation will be done
* by the specified {@link javax.management.MBeanServerBuilder}.
* <p>
* It is recommended that this platform MBeanServer also be used
* to register other application managed beans
* besides the platform MXBeans.
* This will allow all MBeans to be published through the same
* {@code MBeanServer} and hence allow for easier network publishing
* and discovery.
* Name conflicts with the platform MXBeans should be avoided.
*
* @return the platform {@code MBeanServer}; the platform
* MXBeans are registered into the platform {@code MBeanServer}
* at the first time this method is called.
*
* @exception SecurityException if there is a security manager
* and the caller does not have the permission required by
* {@link javax.management.MBeanServerFactory#createMBeanServer}.
*
* @see javax.management.MBeanServerFactory
* @see javax.management.MBeanServerFactory#createMBeanServer
*/
public static synchronized MBeanServer getPlatformMBeanServer() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
Permission perm = new MBeanServerPermission("createMBeanServer");
sm.checkPermission(perm);
}
if (platformMBeanServer == null) {
platformMBeanServer = MBeanServerFactory.createMBeanServer();
for (PlatformComponent pc : PlatformComponent.values()) {
List<? extends PlatformManagedObject> list =
pc.getMXBeans(pc.getMXBeanInterface());
for (PlatformManagedObject o : list) {
// Each PlatformComponent represents one management
// interface. Some MXBean may extend another one.
// The MXBean instances for one platform component
// (returned by pc.getMXBeans()) might be also
// the MXBean instances for another platform component.
// e.g. com.sun.management.GarbageCollectorMXBean
//
// So need to check if an MXBean instance is registered
// before registering into the platform MBeanServer
if (!platformMBeanServer.isRegistered(o.getObjectName())) {
addMXBean(platformMBeanServer, o);
}
}
}
HashMap<ObjectName, DynamicMBean> dynmbeans =
ManagementFactoryHelper.getPlatformDynamicMBeans();
for (Map.Entry<ObjectName, DynamicMBean> e : dynmbeans.entrySet()) {
addDynamicMBean(platformMBeanServer, e.getValue(), e.getKey());
}
for (final PlatformManagedObject o :
ExtendedPlatformComponent.getMXBeans()) {
if (!platformMBeanServer.isRegistered(o.getObjectName())) {
addMXBean(platformMBeanServer, o);
}
}
}
return platformMBeanServer;
}
/**
* Returns a proxy for a platform MXBean interface of a
* given <a href="#MXBeanNames">MXBean name</a>
* that forwards its method calls through the given
* <tt>MBeanServerConnection</tt>.
*
* <p>This method is equivalent to:
* <blockquote>
* {@link java.lang.reflect.Proxy#newProxyInstance
* Proxy.newProxyInstance}<tt>(mxbeanInterface.getClassLoader(),
* new Class[] { mxbeanInterface }, handler)</tt>
* </blockquote>
*
* where <tt>handler</tt> is an {@link java.lang.reflect.InvocationHandler
* InvocationHandler} to which method invocations to the MXBean interface
* are dispatched. This <tt>handler</tt> converts an input parameter
* from an MXBean data type to its mapped open type before forwarding
* to the <tt>MBeanServer</tt> and converts a return value from
* an MXBean method call through the <tt>MBeanServer</tt>
* from an open type to the corresponding return type declared in
* the MXBean interface.
*
* <p>
* If the MXBean is a notification emitter (i.e.,
* it implements
* {@link javax.management.NotificationEmitter NotificationEmitter}),
* both the <tt>mxbeanInterface</tt> and <tt>NotificationEmitter</tt>
* will be implemented by this proxy.
*
* <p>
* <b>Notes:</b>
* <ol>
* <li>Using an MXBean proxy is a convenience remote access to
* a platform MXBean of a running virtual machine. All method
* calls to the MXBean proxy are forwarded to an
* <tt>MBeanServerConnection</tt> where
* {@link java.io.IOException IOException} may be thrown
* when the communication problem occurs with the connector server.
* An application remotely accesses the platform MXBeans using
* proxy should prepare to catch <tt>IOException</tt> as if
* accessing with the <tt>MBeanServerConnector</tt> interface.</li>
*
* <li>When a client application is designed to remotely access MXBeans
* for a running virtual machine whose version is different than
* the version on which the application is running,
* it should prepare to catch
* {@link java.io.InvalidObjectException InvalidObjectException}
* which is thrown when an MXBean proxy receives a name of an
* enum constant which is missing in the enum class loaded in
* the client application. </li>
*
* <li>{@link javax.management.MBeanServerInvocationHandler
* MBeanServerInvocationHandler} or its
* {@link javax.management.MBeanServerInvocationHandler#newProxyInstance
* newProxyInstance} method cannot be used to create
* a proxy for a platform MXBean. The proxy object created
* by <tt>MBeanServerInvocationHandler</tt> does not handle
* the properties of the platform MXBeans described in
* the <a href="#MXBean">class specification</a>.
*</li>
* </ol>
*
* @param connection the <tt>MBeanServerConnection</tt> to forward to.
* @param mxbeanName the name of a platform MXBean within
* <tt>connection</tt> to forward to. <tt>mxbeanName</tt> must be
* in the format of {@link ObjectName ObjectName}.
* @param mxbeanInterface the MXBean interface to be implemented
* by the proxy.
* @param <T> an {@code mxbeanInterface} type parameter
*
* @return a proxy for a platform MXBean interface of a
* given <a href="#MXBeanNames">MXBean name</a>
* that forwards its method calls through the given
* <tt>MBeanServerConnection</tt>, or {@code null} if not exist.
*
* @throws IllegalArgumentException if
* <ul>
* <li><tt>mxbeanName</tt> is not with a valid
* {@link ObjectName ObjectName} format, or</li>
* <li>the named MXBean in the <tt>connection</tt> is
* not a MXBean provided by the platform, or</li>
* <li>the named MXBean is not registered in the
* <tt>MBeanServerConnection</tt>, or</li>
* <li>the named MXBean is not an instance of the given
* <tt>mxbeanInterface</tt></li>
* </ul>
*
* @throws java.io.IOException if a communication problem
* occurred when accessing the <tt>MBeanServerConnection</tt>.
*/
public static <T> T
newPlatformMXBeanProxy(MBeanServerConnection connection,
String mxbeanName,
Class<T> mxbeanInterface)
throws java.io.IOException {
// Only allow MXBean interfaces from rt.jar loaded by the
// bootstrap class loader
final Class<?> cls = mxbeanInterface;
ClassLoader loader =
AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return cls.getClassLoader();
}
});
if (!sun.misc.VM.isSystemDomainLoader(loader)) {
throw new IllegalArgumentException(mxbeanName +
" is not a platform MXBean");
}
try {
final ObjectName objName = new ObjectName(mxbeanName);
// skip the isInstanceOf check for LoggingMXBean
String intfName = mxbeanInterface.getName();
if (!connection.isInstanceOf(objName, intfName)) {
throw new IllegalArgumentException(mxbeanName +
" is not an instance of " + mxbeanInterface);
}
final Class[] interfaces;
// check if the registered MBean is a notification emitter
boolean emitter = connection.isInstanceOf(objName, NOTIF_EMITTER);
// create an MXBean proxy
return JMX.newMXBeanProxy(connection, objName, mxbeanInterface,
emitter);
} catch (InstanceNotFoundException|MalformedObjectNameException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Returns the platform MXBean implementing
* the given {@code mxbeanInterface} which is specified
* to have one single instance in the Java virtual machine.
* This method may return {@code null} if the management interface
* is not implemented in the Java virtual machine (for example,
* a Java virtual machine with no compilation system does not
* implement {@link CompilationMXBean});
* otherwise, this method is equivalent to calling:
* <pre>
* {@link #getPlatformMXBeans(Class)
* getPlatformMXBeans(mxbeanInterface)}.get(0);
* </pre>
*
* @param mxbeanInterface a management interface for a platform
* MXBean with one single instance in the Java virtual machine
* if implemented.
* @param <T> an {@code mxbeanInterface} type parameter
*
* @return the platform MXBean that implements
* {@code mxbeanInterface}, or {@code null} if not exist.
*
* @throws IllegalArgumentException if {@code mxbeanInterface}
* is not a platform management interface or
* not a singleton platform MXBean.
*
* @since 1.7
*/
public static <T extends PlatformManagedObject>
T getPlatformMXBean(Class<T> mxbeanInterface) {
PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface);
if (pc == null) {
T mbean = ExtendedPlatformComponent.getMXBean(mxbeanInterface);
if (mbean != null) {
return mbean;
}
throw new IllegalArgumentException(mxbeanInterface.getName() +
" is not a platform management interface");
}
if (!pc.isSingleton())
throw new IllegalArgumentException(mxbeanInterface.getName() +
" can have zero or more than one instances");
return pc.getSingletonMXBean(mxbeanInterface);
}
/**
* Returns the list of platform MXBeans implementing
* the given {@code mxbeanInterface} in the Java
* virtual machine.
* The returned list may contain zero, one, or more instances.
* The number of instances in the returned list is defined
* in the specification of the given management interface.
* The order is undefined and there is no guarantee that
* the list returned is in the same order as previous invocations.
*
* @param mxbeanInterface a management interface for a platform
* MXBean
* @param <T> an {@code mxbeanInterface} type parameter
*
* @return the list of platform MXBeans that implement
* {@code mxbeanInterface}.
*
* @throws IllegalArgumentException if {@code mxbeanInterface}
* is not a platform management interface.
*
* @since 1.7
*/
public static <T extends PlatformManagedObject> List<T>
getPlatformMXBeans(Class<T> mxbeanInterface) {
PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface);
if (pc == null) {
T mbean = ExtendedPlatformComponent.getMXBean(mxbeanInterface);
if (mbean != null) {
return Collections.singletonList(mbean);
}
throw new IllegalArgumentException(mxbeanInterface.getName() +
" is not a platform management interface");
}
return Collections.unmodifiableList(pc.getMXBeans(mxbeanInterface));
}
/**
* Returns the platform MXBean proxy for
* {@code mxbeanInterface} which is specified to have one single
* instance in a Java virtual machine and the proxy will
* forward the method calls through the given {@code MBeanServerConnection}.
* This method may return {@code null} if the management interface
* is not implemented in the Java virtual machine being monitored
* (for example, a Java virtual machine with no compilation system
* does not implement {@link CompilationMXBean});
* otherwise, this method is equivalent to calling:
* <pre>
* {@link #getPlatformMXBeans(MBeanServerConnection, Class)
* getPlatformMXBeans(connection, mxbeanInterface)}.get(0);
* </pre>
*
* @param connection the {@code MBeanServerConnection} to forward to.
* @param mxbeanInterface a management interface for a platform
* MXBean with one single instance in the Java virtual machine
* being monitored, if implemented.
* @param <T> an {@code mxbeanInterface} type parameter
*
* @return the platform MXBean proxy for
* forwarding the method calls of the {@code mxbeanInterface}
* through the given {@code MBeanServerConnection},
* or {@code null} if not exist.
*
* @throws IllegalArgumentException if {@code mxbeanInterface}
* is not a platform management interface or
* not a singleton platform MXBean.
* @throws java.io.IOException if a communication problem
* occurred when accessing the {@code MBeanServerConnection}.
*
* @see #newPlatformMXBeanProxy
* @since 1.7
*/
public static <T extends PlatformManagedObject>
T getPlatformMXBean(MBeanServerConnection connection,
Class<T> mxbeanInterface)
throws java.io.IOException
{
PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface);
if (pc == null) {
T mbean = ExtendedPlatformComponent.getMXBean(mxbeanInterface);
if (mbean != null) {
ObjectName on = mbean.getObjectName();
return ManagementFactory.newPlatformMXBeanProxy(connection,
on.getCanonicalName(),
mxbeanInterface);
}
throw new IllegalArgumentException(mxbeanInterface.getName() +
" is not a platform management interface");
}
if (!pc.isSingleton())
throw new IllegalArgumentException(mxbeanInterface.getName() +
" can have zero or more than one instances");
return pc.getSingletonMXBean(connection, mxbeanInterface);
}
/**
* Returns the list of the platform MXBean proxies for
* forwarding the method calls of the {@code mxbeanInterface}
* through the given {@code MBeanServerConnection}.
* The returned list may contain zero, one, or more instances.
* The number of instances in the returned list is defined
* in the specification of the given management interface.
* The order is undefined and there is no guarantee that
* the list returned is in the same order as previous invocations.
*
* @param connection the {@code MBeanServerConnection} to forward to.
* @param mxbeanInterface a management interface for a platform
* MXBean
* @param <T> an {@code mxbeanInterface} type parameter
*
* @return the list of platform MXBean proxies for
* forwarding the method calls of the {@code mxbeanInterface}
* through the given {@code MBeanServerConnection}.
*
* @throws IllegalArgumentException if {@code mxbeanInterface}
* is not a platform management interface.
*
* @throws java.io.IOException if a communication problem
* occurred when accessing the {@code MBeanServerConnection}.
*
* @see #newPlatformMXBeanProxy
* @since 1.7
*/
public static <T extends PlatformManagedObject>
List<T> getPlatformMXBeans(MBeanServerConnection connection,
Class<T> mxbeanInterface)
throws java.io.IOException
{
PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface);
if (pc == null) {
T mbean = ExtendedPlatformComponent.getMXBean(mxbeanInterface);
if (mbean != null) {
ObjectName on = mbean.getObjectName();
T proxy = ManagementFactory.newPlatformMXBeanProxy(connection,
on.getCanonicalName(), mxbeanInterface);
return Collections.singletonList(proxy);
}
throw new IllegalArgumentException(mxbeanInterface.getName() +
" is not a platform management interface");
}
return Collections.unmodifiableList(pc.getMXBeans(connection, mxbeanInterface));
}
/**
* Returns the set of {@code Class} objects, subinterface of
* {@link PlatformManagedObject}, representing
* all management interfaces for
* monitoring and managing the Java platform.
*
* @return the set of {@code Class} objects, subinterface of
* {@link PlatformManagedObject} representing
* the management interfaces for
* monitoring and managing the Java platform.
*
* @since 1.7
*/
public static Set<Class<? extends PlatformManagedObject>>
getPlatformManagementInterfaces()
{
Set<Class<? extends PlatformManagedObject>> result =
new HashSet<>();
for (PlatformComponent component: PlatformComponent.values()) {
result.add(component.getMXBeanInterface());
}
return Collections.unmodifiableSet(result);
}
private static final String NOTIF_EMITTER =
"javax.management.NotificationEmitter";
/**
* Registers an MXBean.
*/
private static void addMXBean(final MBeanServer mbs, final PlatformManagedObject pmo) {
// Make DynamicMBean out of MXBean by wrapping it with a StandardMBean
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
public Void run() throws InstanceAlreadyExistsException,
MBeanRegistrationException,
NotCompliantMBeanException {
final DynamicMBean dmbean;
if (pmo instanceof DynamicMBean) {
dmbean = DynamicMBean.class.cast(pmo);
} else if (pmo instanceof NotificationEmitter) {
dmbean = new StandardEmitterMBean(pmo, null, true, (NotificationEmitter) pmo);
} else {
dmbean = new StandardMBean(pmo, null, true);
}
mbs.registerMBean(dmbean, pmo.getObjectName());
return null;
}
});
} catch (PrivilegedActionException e) {
throw new RuntimeException(e.getException());
}
}
/**
* Registers a DynamicMBean.
*/
private static void addDynamicMBean(final MBeanServer mbs,
final DynamicMBean dmbean,
final ObjectName on) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws InstanceAlreadyExistsException,
MBeanRegistrationException,
NotCompliantMBeanException {
mbs.registerMBean(dmbean, on);
return null;
}
});
} catch (PrivilegedActionException e) {
throw new RuntimeException(e.getException());
}
}
}

View File

@@ -0,0 +1,126 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
/**
* The permission which the SecurityManager will check when code
* that is running with a SecurityManager calls methods defined
* in the management interface for the Java platform.
* <P>
* The following table
* provides a summary description of what the permission allows,
* and discusses the risks of granting code the permission.
*
* <table border=1 cellpadding=5 summary="Table shows permission target name, what the permission allows, and associated risks">
* <tr>
* <th>Permission Target Name</th>
* <th>What the Permission Allows</th>
* <th>Risks of Allowing this Permission</th>
* </tr>
*
* <tr>
* <td>control</td>
* <td>Ability to control the runtime characteristics of the Java virtual
* machine, for example, enabling and disabling the verbose output for
* the class loading or memory system, setting the threshold of a memory
* pool, and enabling and disabling the thread contention monitoring
* support. Some actions controlled by this permission can disclose
* information about the running application, like the -verbose:class
* flag.
* </td>
* <td>This allows an attacker to control the runtime characteristics
* of the Java virtual machine and cause the system to misbehave. An
* attacker can also access some information related to the running
* application.
* </td>
* </tr>
* <tr>
* <td>monitor</td>
* <td>Ability to retrieve runtime information about
* the Java virtual machine such as thread
* stack trace, a list of all loaded class names, and input arguments
* to the Java virtual machine.</td>
* <td>This allows malicious code to monitor runtime information and
* uncover vulnerabilities.</td>
* </tr>
*
* </table>
*
* <p>
* Programmers do not normally create ManagementPermission objects directly.
* Instead they are created by the security policy code based on reading
* the security policy file.
*
* @author Mandy Chung
* @since 1.5
*
* @see java.security.BasicPermission
* @see java.security.Permission
* @see java.security.Permissions
* @see java.security.PermissionCollection
* @see java.lang.SecurityManager
*
*/
public final class ManagementPermission extends java.security.BasicPermission {
private static final long serialVersionUID = 1897496590799378737L;
/**
* Constructs a ManagementPermission with the specified name.
*
* @param name Permission name. Must be either "monitor" or "control".
*
* @throws NullPointerException if <code>name</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is empty or invalid.
*/
public ManagementPermission(String name) {
super(name);
if (!name.equals("control") && !name.equals("monitor")) {
throw new IllegalArgumentException("name: " + name);
}
}
/**
* Constructs a new ManagementPermission object.
*
* @param name Permission name. Must be either "monitor" or "control".
* @param actions Must be either null or the empty string.
*
* @throws NullPointerException if <code>name</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is empty or
* if arguments are invalid.
*/
public ManagementPermission(String name, String actions)
throws IllegalArgumentException {
super(name);
if (!name.equals("control") && !name.equals("monitor")) {
throw new IllegalArgumentException("name: " + name);
}
if (actions != null && actions.length() > 0) {
throw new IllegalArgumentException("actions: " + actions);
}
}
}

View File

@@ -0,0 +1,304 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
import javax.management.openmbean.CompositeData;
/**
* The management interface for the memory system of
* the Java virtual machine.
*
* <p> A Java virtual machine has a single instance of the implementation
* class of this interface. This instance implementing this interface is
* an <a href="ManagementFactory.html#MXBean">MXBean</a>
* that can be obtained by calling
* the {@link ManagementFactory#getMemoryMXBean} method or
* from the {@link ManagementFactory#getPlatformMBeanServer
* platform <tt>MBeanServer</tt>} method.
*
* <p>The <tt>ObjectName</tt> for uniquely identifying the MXBean for
* the memory system within an MBeanServer is:
* <blockquote>
* {@link ManagementFactory#MEMORY_MXBEAN_NAME
* <tt>java.lang:type=Memory</tt>}
* </blockquote>
*
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <h3> Memory </h3>
* The memory system of the Java virtual machine manages
* the following kinds of memory:
*
* <h3> 1. Heap </h3>
* The Java virtual machine has a <i>heap</i> that is the runtime
* data area from which memory for all class instances and arrays
* are allocated. It is created at the Java virtual machine start-up.
* Heap memory for objects is reclaimed by an automatic memory management
* system which is known as a <i>garbage collector</i>.
*
* <p>The heap may be of a fixed size or may be expanded and shrunk.
* The memory for the heap does not need to be contiguous.
*
* <h3> 2. Non-Heap Memory</h3>
* The Java virtual machine manages memory other than the heap
* (referred as <i>non-heap memory</i>).
*
* <p> The Java virtual machine has a <i>method area</i> that is shared
* among all threads.
* The method area belongs to non-heap memory. It stores per-class structures
* such as a runtime constant pool, field and method data, and the code for
* methods and constructors. It is created at the Java virtual machine
* start-up.
*
* <p> The method area is logically part of the heap but a Java virtual
* machine implementation may choose not to either garbage collect
* or compact it. Similar to the heap, the method area may be of a
* fixed size or may be expanded and shrunk. The memory for the
* method area does not need to be contiguous.
*
* <p>In addition to the method area, a Java virtual machine
* implementation may require memory for internal processing or
* optimization which also belongs to non-heap memory.
* For example, the JIT compiler requires memory for storing the native
* machine code translated from the Java virtual machine code for
* high performance.
*
* <h3>Memory Pools and Memory Managers</h3>
* {@link MemoryPoolMXBean Memory pools} and
* {@link MemoryManagerMXBean memory managers} are the abstract entities
* that monitor and manage the memory system
* of the Java virtual machine.
*
* <p>A memory pool represents a memory area that the Java virtual machine
* manages. The Java virtual machine has at least one memory pool
* and it may create or remove memory pools during execution.
* A memory pool can belong to either the heap or the non-heap memory.
*
* <p>A memory manager is responsible for managing one or more memory pools.
* The garbage collector is one type of memory manager responsible
* for reclaiming memory occupied by unreachable objects. A Java virtual
* machine may have one or more memory managers. It may
* add or remove memory managers during execution.
* A memory pool can be managed by more than one memory manager.
*
* <h3>Memory Usage Monitoring</h3>
*
* Memory usage is a very important monitoring attribute for the memory system.
* The memory usage, for example, could indicate:
* <ul>
* <li>the memory usage of an application,</li>
* <li>the workload being imposed on the automatic memory management system,</li>
* <li>potential memory leakage.</li>
* </ul>
*
* <p>
* The memory usage can be monitored in three ways:
* <ul>
* <li>Polling</li>
* <li>Usage Threshold Notification</li>
* <li>Collection Usage Threshold Notification</li>
* </ul>
*
* Details are specified in the {@link MemoryPoolMXBean} interface.
*
* <p>The memory usage monitoring mechanism is intended for load-balancing
* or workload distribution use. For example, an application would stop
* receiving any new workload when its memory usage exceeds a
* certain threshold. It is not intended for an application to detect
* and recover from a low memory condition.
*
* <h3>Notifications</h3>
*
* <p>This <tt>MemoryMXBean</tt> is a
* {@link javax.management.NotificationEmitter NotificationEmitter}
* that emits two types of memory {@link javax.management.Notification
* notifications} if any one of the memory pools
* supports a <a href="MemoryPoolMXBean.html#UsageThreshold">usage threshold</a>
* or a <a href="MemoryPoolMXBean.html#CollectionThreshold">collection usage
* threshold</a> which can be determined by calling the
* {@link MemoryPoolMXBean#isUsageThresholdSupported} and
* {@link MemoryPoolMXBean#isCollectionUsageThresholdSupported} methods.
* <ul>
* <li>{@link MemoryNotificationInfo#MEMORY_THRESHOLD_EXCEEDED
* usage threshold exceeded notification} - for notifying that
* the memory usage of a memory pool is increased and has reached
* or exceeded its
* <a href="MemoryPoolMXBean.html#UsageThreshold"> usage threshold</a> value.
* </li>
* <li>{@link MemoryNotificationInfo#MEMORY_COLLECTION_THRESHOLD_EXCEEDED
* collection usage threshold exceeded notification} - for notifying that
* the memory usage of a memory pool is greater than or equal to its
* <a href="MemoryPoolMXBean.html#CollectionThreshold">
* collection usage threshold</a> after the Java virtual machine
* has expended effort in recycling unused objects in that
* memory pool.</li>
* </ul>
*
* <p>
* The notification emitted is a {@link javax.management.Notification}
* instance whose {@link javax.management.Notification#setUserData
* user data} is set to a {@link CompositeData CompositeData}
* that represents a {@link MemoryNotificationInfo} object
* containing information about the memory pool when the notification
* was constructed. The <tt>CompositeData</tt> contains the attributes
* as described in {@link MemoryNotificationInfo#from
* MemoryNotificationInfo}.
*
* <hr>
* <h3>NotificationEmitter</h3>
* The <tt>MemoryMXBean</tt> object returned by
* {@link ManagementFactory#getMemoryMXBean} implements
* the {@link javax.management.NotificationEmitter NotificationEmitter}
* interface that allows a listener to be registered within the
* <tt>MemoryMXBean</tt> as a notification listener.
*
* Below is an example code that registers a <tt>MyListener</tt> to handle
* notification emitted by the <tt>MemoryMXBean</tt>.
*
* <blockquote><pre>
* class MyListener implements javax.management.NotificationListener {
* public void handleNotification(Notification notif, Object handback) {
* // handle notification
* ....
* }
* }
*
* MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
* NotificationEmitter emitter = (NotificationEmitter) mbean;
* MyListener listener = new MyListener();
* emitter.addNotificationListener(listener, null, null);
* </pre></blockquote>
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a>
* @see <a href="package-summary.html#examples">
* Ways to Access MXBeans</a>
*
* @author Mandy Chung
* @since 1.5
*/
public interface MemoryMXBean extends PlatformManagedObject {
/**
* Returns the approximate number of objects for which
* finalization is pending.
*
* @return the approximate number objects for which finalization
* is pending.
*/
public int getObjectPendingFinalizationCount();
/**
* Returns the current memory usage of the heap that
* is used for object allocation. The heap consists
* of one or more memory pools. The <tt>used</tt>
* and <tt>committed</tt> size of the returned memory
* usage is the sum of those values of all heap memory pools
* whereas the <tt>init</tt> and <tt>max</tt> size of the
* returned memory usage represents the setting of the heap
* memory which may not be the sum of those of all heap
* memory pools.
* <p>
* The amount of used memory in the returned memory usage
* is the amount of memory occupied by both live objects
* and garbage objects that have not been collected, if any.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>MemoryUsage</tt> is
* <tt>CompositeData</tt> with attributes as specified in
* {@link MemoryUsage#from MemoryUsage}.
*
* @return a {@link MemoryUsage} object representing
* the heap memory usage.
*/
public MemoryUsage getHeapMemoryUsage();
/**
* Returns the current memory usage of non-heap memory that
* is used by the Java virtual machine.
* The non-heap memory consists of one or more memory pools.
* The <tt>used</tt> and <tt>committed</tt> size of the
* returned memory usage is the sum of those values of
* all non-heap memory pools whereas the <tt>init</tt>
* and <tt>max</tt> size of the returned memory usage
* represents the setting of the non-heap
* memory which may not be the sum of those of all non-heap
* memory pools.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>MemoryUsage</tt> is
* <tt>CompositeData</tt> with attributes as specified in
* {@link MemoryUsage#from MemoryUsage}.
*
* @return a {@link MemoryUsage} object representing
* the non-heap memory usage.
*/
public MemoryUsage getNonHeapMemoryUsage();
/**
* Tests if verbose output for the memory system is enabled.
*
* @return <tt>true</tt> if verbose output for the memory
* system is enabled; <tt>false</tt> otherwise.
*/
public boolean isVerbose();
/**
* Enables or disables verbose output for the memory
* system. The verbose output information and the output stream
* to which the verbose information is emitted are implementation
* dependent. Typically, a Java virtual machine implementation
* prints a message whenever it frees memory at garbage collection.
*
* <p>
* Each invocation of this method enables or disables verbose
* output globally.
*
* @param value <tt>true</tt> to enable verbose output;
* <tt>false</tt> to disable.
*
* @exception java.lang.SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("control").
*/
public void setVerbose(boolean value);
/**
* Runs the garbage collector.
* The call <code>gc()</code> is effectively equivalent to the
* call:
* <blockquote><pre>
* System.gc()
* </pre></blockquote>
*
* @see java.lang.System#gc()
*/
public void gc();
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
/**
* The management interface for a memory manager.
* A memory manager manages one or more memory pools of the
* Java virtual machine.
*
* <p> A Java virtual machine has one or more memory managers.
* An instance implementing this interface is
* an <a href="ManagementFactory.html#MXBean">MXBean</a>
* that can be obtained by calling
* the {@link ManagementFactory#getMemoryManagerMXBeans} method or
* from the {@link ManagementFactory#getPlatformMBeanServer
* platform <tt>MBeanServer</tt>} method.
*
* <p>The <tt>ObjectName</tt> for uniquely identifying the MXBean for
* a memory manager within an MBeanServer is:
* <blockquote>
* {@link ManagementFactory#MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE
* <tt>java.lang:type=MemoryManager</tt>}<tt>,name=</tt><i>manager's name</i>
* </blockquote>
*
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see MemoryMXBean
*
* @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a>
* @see <a href="package-summary.html#examples">
* Ways to Access MXBeans</a>
*
* @author Mandy Chung
* @since 1.5
*/
public interface MemoryManagerMXBean extends PlatformManagedObject {
/**
* Returns the name representing this memory manager.
*
* @return the name of this memory manager.
*/
public String getName();
/**
* Tests if this memory manager is valid in the Java virtual
* machine. A memory manager becomes invalid once the Java virtual
* machine removes it from the memory system.
*
* @return <tt>true</tt> if the memory manager is valid in the
* Java virtual machine;
* <tt>false</tt> otherwise.
*/
public boolean isValid();
/**
* Returns the name of memory pools that this memory manager manages.
*
* @return an array of <tt>String</tt> objects, each is
* the name of a memory pool that this memory manager manages.
*/
public String[] getMemoryPoolNames();
}

View File

@@ -0,0 +1,256 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
import javax.management.openmbean.CompositeData;
import sun.management.MemoryNotifInfoCompositeData;
/**
* The information about a memory notification.
*
* <p>
* A memory notification is emitted by {@link MemoryMXBean}
* when the Java virtual machine detects that the memory usage
* of a memory pool is exceeding a threshold value.
* The notification emitted will contain the memory notification
* information about the detected condition:
* <ul>
* <li>The name of the memory pool.</li>
* <li>The memory usage of the memory pool when the notification
* was constructed.</li>
* <li>The number of times that the memory usage has crossed
* a threshold when the notification was constructed.
* For usage threshold notifications, this count will be the
* {@link MemoryPoolMXBean#getUsageThresholdCount usage threshold
* count}. For collection threshold notifications,
* this count will be the
* {@link MemoryPoolMXBean#getCollectionUsageThresholdCount
* collection usage threshold count}.
* </li>
* </ul>
*
* <p>
* A {@link CompositeData CompositeData} representing
* the <tt>MemoryNotificationInfo</tt> object
* is stored in the
* {@link javax.management.Notification#setUserData user data}
* of a {@link javax.management.Notification notification}.
* The {@link #from from} method is provided to convert from
* a <tt>CompositeData</tt> to a <tt>MemoryNotificationInfo</tt>
* object. For example:
*
* <blockquote><pre>
* Notification notif;
*
* // receive the notification emitted by MemoryMXBean and set to notif
* ...
*
* String notifType = notif.getType();
* if (notifType.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED) ||
* notifType.equals(MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
* // retrieve the memory notification information
* CompositeData cd = (CompositeData) notif.getUserData();
* MemoryNotificationInfo info = MemoryNotificationInfo.from(cd);
* ....
* }
* </pre></blockquote>
*
* <p>
* The types of notifications emitted by <tt>MemoryMXBean</tt> are:
* <ul>
* <li>A {@link #MEMORY_THRESHOLD_EXCEEDED
* usage threshold exceeded notification}.
* <br>This notification will be emitted when
* the memory usage of a memory pool is increased and has reached
* or exceeded its
* <a href="MemoryPoolMXBean.html#UsageThreshold"> usage threshold</a> value.
* Subsequent crossing of the usage threshold value does not cause
* further notification until the memory usage has returned
* to become less than the usage threshold value.
* <p></li>
* <li>A {@link #MEMORY_COLLECTION_THRESHOLD_EXCEEDED
* collection usage threshold exceeded notification}.
* <br>This notification will be emitted when
* the memory usage of a memory pool is greater than or equal to its
* <a href="MemoryPoolMXBean.html#CollectionThreshold">
* collection usage threshold</a> after the Java virtual machine
* has expended effort in recycling unused objects in that
* memory pool.</li>
* </ul>
*
* @author Mandy Chung
* @since 1.5
*
*/
public class MemoryNotificationInfo {
private final String poolName;
private final MemoryUsage usage;
private final long count;
/**
* Notification type denoting that
* the memory usage of a memory pool has
* reached or exceeded its
* <a href="MemoryPoolMXBean.html#UsageThreshold"> usage threshold</a> value.
* This notification is emitted by {@link MemoryMXBean}.
* Subsequent crossing of the usage threshold value does not cause
* further notification until the memory usage has returned
* to become less than the usage threshold value.
* The value of this notification type is
* <tt>java.management.memory.threshold.exceeded</tt>.
*/
public static final String MEMORY_THRESHOLD_EXCEEDED =
"java.management.memory.threshold.exceeded";
/**
* Notification type denoting that
* the memory usage of a memory pool is greater than or equal to its
* <a href="MemoryPoolMXBean.html#CollectionThreshold">
* collection usage threshold</a> after the Java virtual machine
* has expended effort in recycling unused objects in that
* memory pool.
* This notification is emitted by {@link MemoryMXBean}.
* The value of this notification type is
* <tt>java.management.memory.collection.threshold.exceeded</tt>.
*/
public static final String MEMORY_COLLECTION_THRESHOLD_EXCEEDED =
"java.management.memory.collection.threshold.exceeded";
/**
* Constructs a <tt>MemoryNotificationInfo</tt> object.
*
* @param poolName The name of the memory pool which triggers this notification.
* @param usage Memory usage of the memory pool.
* @param count The threshold crossing count.
*/
public MemoryNotificationInfo(String poolName,
MemoryUsage usage,
long count) {
if (poolName == null) {
throw new NullPointerException("Null poolName");
}
if (usage == null) {
throw new NullPointerException("Null usage");
}
this.poolName = poolName;
this.usage = usage;
this.count = count;
}
MemoryNotificationInfo(CompositeData cd) {
MemoryNotifInfoCompositeData.validateCompositeData(cd);
this.poolName = MemoryNotifInfoCompositeData.getPoolName(cd);
this.usage = MemoryNotifInfoCompositeData.getUsage(cd);
this.count = MemoryNotifInfoCompositeData.getCount(cd);
}
/**
* Returns the name of the memory pool that triggers this notification.
* The memory pool usage has crossed a threshold.
*
* @return the name of the memory pool that triggers this notification.
*/
public String getPoolName() {
return poolName;
}
/**
* Returns the memory usage of the memory pool
* when this notification was constructed.
*
* @return the memory usage of the memory pool
* when this notification was constructed.
*/
public MemoryUsage getUsage() {
return usage;
}
/**
* Returns the number of times that the memory usage has crossed
* a threshold when the notification was constructed.
* For usage threshold notifications, this count will be the
* {@link MemoryPoolMXBean#getUsageThresholdCount threshold
* count}. For collection threshold notifications,
* this count will be the
* {@link MemoryPoolMXBean#getCollectionUsageThresholdCount
* collection usage threshold count}.
*
* @return the number of times that the memory usage has crossed
* a threshold when the notification was constructed.
*/
public long getCount() {
return count;
}
/**
* Returns a <tt>MemoryNotificationInfo</tt> object represented by the
* given <tt>CompositeData</tt>.
* The given <tt>CompositeData</tt> must contain
* the following attributes:
* <blockquote>
* <table border summary="The attributes and the types the given CompositeData contains">
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
* </tr>
* <tr>
* <td>poolName</td>
* <td><tt>java.lang.String</tt></td>
* </tr>
* <tr>
* <td>usage</td>
* <td><tt>javax.management.openmbean.CompositeData</tt></td>
* </tr>
* <tr>
* <td>count</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* </table>
* </blockquote>
*
* @param cd <tt>CompositeData</tt> representing a
* <tt>MemoryNotificationInfo</tt>
*
* @throws IllegalArgumentException if <tt>cd</tt> does not
* represent a <tt>MemoryNotificationInfo</tt> object.
*
* @return a <tt>MemoryNotificationInfo</tt> object represented
* by <tt>cd</tt> if <tt>cd</tt> is not <tt>null</tt>;
* <tt>null</tt> otherwise.
*/
public static MemoryNotificationInfo from(CompositeData cd) {
if (cd == null) {
return null;
}
if (cd instanceof MemoryNotifInfoCompositeData) {
return ((MemoryNotifInfoCompositeData) cd).getMemoryNotifInfo();
} else {
return new MemoryNotificationInfo(cd);
}
}
}

View File

@@ -0,0 +1,643 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
/**
* The management interface for a memory pool. A memory pool
* represents the memory resource managed by the Java virtual machine
* and is managed by one or more {@link MemoryManagerMXBean memory managers}.
*
* <p> A Java virtual machine has one or more instances of the
* implementation class of this interface. An instance
* implementing this interface is
* an <a href="ManagementFactory.html#MXBean">MXBean</a>
* that can be obtained by calling
* the {@link ManagementFactory#getMemoryPoolMXBeans} method or
* from the {@link ManagementFactory#getPlatformMBeanServer
* platform <tt>MBeanServer</tt>} method.
*
* <p>The <tt>ObjectName</tt> for uniquely identifying the MXBean for
* a memory pool within an <tt>MBeanServer</tt> is:
* <blockquote>
* {@link ManagementFactory#MEMORY_POOL_MXBEAN_DOMAIN_TYPE
* <tt>java.lang:type=MemoryPool</tt>}<tt>,name=</tt><i>pool's name</i>
* </blockquote>
*
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <h3>Memory Type</h3>
* <p>The Java virtual machine has a heap for object allocation and also
* maintains non-heap memory for the method area and the Java virtual
* machine execution. The Java virtual machine can have one or more
* memory pools. Each memory pool represents a memory area
* of one of the following types:
* <ul>
* <li>{@link MemoryType#HEAP heap}</li>
* <li>{@link MemoryType#NON_HEAP non-heap}</li>
* </ul>
*
* <h3>Memory Usage Monitoring</h3>
*
* A memory pool has the following attributes:
* <ul>
* <li><a href="#Usage">Memory usage</a></li>
* <li><a href="#PeakUsage">Peak memory usage</a></li>
* <li><a href="#UsageThreshold">Usage Threshold</a></li>
* <li><a href="#CollectionThreshold">Collection Usage Threshold</a>
* (only supported by some <em>garbage-collected</em> memory pools)</li>
* </ul>
*
* <h3><a name="Usage">1. Memory Usage</a></h3>
*
* The {@link #getUsage} method provides an estimate
* of the current usage of a memory pool.
* For a garbage-collected memory pool, the amount of used memory
* includes the memory occupied by all objects in the pool
* including both <em>reachable</em> and <em>unreachable</em> objects.
*
* <p>In general, this method is a lightweight operation for getting
* an approximate memory usage. For some memory pools, for example,
* when objects are not packed contiguously, this method may be
* an expensive operation that requires some computation to determine
* the current memory usage. An implementation should document when
* this is the case.
*
* <h3><a name="PeakUsage">2. Peak Memory Usage</a></h3>
*
* The Java virtual machine maintains the peak memory usage of a memory
* pool since the virtual machine was started or the peak was reset.
* The peak memory usage is returned by the {@link #getPeakUsage} method
* and reset by calling the {@link #resetPeakUsage} method.
*
* <h3><a name="UsageThreshold">3. Usage Threshold</a></h3>
*
* Each memory pool has a manageable attribute
* called the <i>usage threshold</i> which has a default value supplied
* by the Java virtual machine. The default value is platform-dependent.
* The usage threshold can be set via the
* {@link #setUsageThreshold setUsageThreshold} method.
* If the threshold is set to a positive value, the usage threshold crossing
* checking is enabled in this memory pool.
* If the usage threshold is set to zero, usage
* threshold crossing checking on this memory pool is disabled.
* The {@link MemoryPoolMXBean#isUsageThresholdSupported} method can
* be used to determine if this functionality is supported.
* <p>
* A Java virtual machine performs usage threshold crossing checking on a
* memory pool basis at its best appropriate time, typically,
* at garbage collection time.
* Each memory pool maintains a {@link #getUsageThresholdCount
* usage threshold count} that will get incremented
* every time when the Java virtual machine
* detects that the memory pool usage is crossing the threshold.
* <p>
* This manageable usage threshold attribute is designed for monitoring the
* increasing trend of memory usage with low overhead.
* Usage threshold may not be appropriate for some memory pools.
* For example, a generational garbage collector, a common garbage collection
* algorithm used in many Java virtual machine implementations,
* manages two or more generations segregating objects by age.
* Most of the objects are allocated in
* the <em>youngest generation</em> (say a nursery memory pool).
* The nursery memory pool is designed to be filled up and
* collecting the nursery memory pool will free most of its memory space
* since it is expected to contain mostly short-lived objects
* and mostly are unreachable at garbage collection time.
* In this case, it is more appropriate for the nursery memory pool
* not to support a usage threshold. In addition,
* if the cost of an object allocation
* in one memory pool is very low (for example, just atomic pointer exchange),
* the Java virtual machine would probably not support the usage threshold
* for that memory pool since the overhead in comparing the usage with
* the threshold is higher than the cost of object allocation.
*
* <p>
* The memory usage of the system can be monitored using
* <a href="#Polling">polling</a> or
* <a href="#ThresholdNotification">threshold notification</a> mechanisms.
*
* <ol type="a">
* <li><a name="Polling"><b>Polling</b></a>
* <p>
* An application can continuously monitor its memory usage
* by calling either the {@link #getUsage} method for all
* memory pools or the {@link #isUsageThresholdExceeded} method
* for those memory pools that support a usage threshold.
* Below is example code that has a thread dedicated for
* task distribution and processing. At every interval,
* it will determine if it should receive and process new tasks based
* on its memory usage. If the memory usage exceeds its usage threshold,
* it will redistribute all outstanding tasks to other VMs and
* stop receiving new tasks until the memory usage returns
* below its usage threshold.
*
* <pre>
* // Assume the usage threshold is supported for this pool.
* // Set the threshold to myThreshold above which no new tasks
* // should be taken.
* pool.setUsageThreshold(myThreshold);
* ....
*
* boolean lowMemory = false;
* while (true) {
* if (pool.isUsageThresholdExceeded()) {
* // potential low memory, so redistribute tasks to other VMs
* lowMemory = true;
* redistributeTasks();
* // stop receiving new tasks
* stopReceivingTasks();
* } else {
* if (lowMemory) {
* // resume receiving tasks
* lowMemory = false;
* resumeReceivingTasks();
* }
* // processing outstanding task
* ...
* }
* // sleep for sometime
* try {
* Thread.sleep(sometime);
* } catch (InterruptedException e) {
* ...
* }
* }
* </pre>
*
* <hr>
* The above example does not differentiate the case where
* the memory usage has temporarily dropped below the usage threshold
* from the case where the memory usage remains above the threshold
* between two iterations. The usage threshold count returned by
* the {@link #getUsageThresholdCount} method
* can be used to determine
* if the memory usage has returned below the threshold
* between two polls.
* <p>
* Below shows another example that takes some action if a
* memory pool is under low memory and ignores the memory usage
* changes during the action processing time.
*
* <pre>
* // Assume the usage threshold is supported for this pool.
* // Set the threshold to myThreshold which determines if
* // the application will take some action under low memory condition.
* pool.setUsageThreshold(myThreshold);
*
* int prevCrossingCount = 0;
* while (true) {
* // A busy loop to detect when the memory usage
* // has exceeded the threshold.
* while (!pool.isUsageThresholdExceeded() ||
* pool.getUsageThresholdCount() == prevCrossingCount) {
* try {
* Thread.sleep(sometime)
* } catch (InterruptException e) {
* ....
* }
* }
*
* // Do some processing such as check for memory usage
* // and issue a warning
* ....
*
* // Gets the current threshold count. The busy loop will then
* // ignore any crossing of threshold happens during the processing.
* prevCrossingCount = pool.getUsageThresholdCount();
* }
* </pre><hr>
* </li>
* <li><a name="ThresholdNotification"><b>Usage Threshold Notifications</b></a>
* <p>
* Usage threshold notification will be emitted by {@link MemoryMXBean}.
* When the Java virtual machine detects that the memory usage of
* a memory pool has reached or exceeded the usage threshold
* the virtual machine will trigger the <tt>MemoryMXBean</tt> to emit an
* {@link MemoryNotificationInfo#MEMORY_THRESHOLD_EXCEEDED
* usage threshold exceeded notification}.
* Another usage threshold exceeded notification will not be
* generated until the usage has fallen below the threshold and
* then exceeded it again.
* <p>
* Below is an example code implementing the same logic as the
* first example above but using the usage threshold notification
* mechanism to detect low memory conditions instead of polling.
* In this example code, upon receiving notification, the notification
* listener notifies another thread to perform the actual action
* such as to redistribute outstanding tasks, stop receiving tasks,
* or resume receiving tasks.
* The <tt>handleNotification</tt> method should be designed to
* do a very minimal amount of work and return without delay to avoid
* causing delay in delivering subsequent notifications. Time-consuming
* actions should be performed by a separate thread.
* The notification listener may be invoked by multiple threads
* concurrently; so the tasks performed by the listener
* should be properly synchronized.
*
* <pre>
* class MyListener implements javax.management.NotificationListener {
* public void handleNotification(Notification notification, Object handback) {
* String notifType = notification.getType();
* if (notifType.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
* // potential low memory, notify another thread
* // to redistribute outstanding tasks to other VMs
* // and stop receiving new tasks.
* lowMemory = true;
* notifyAnotherThread(lowMemory);
* }
* }
* }
*
* // Register MyListener with MemoryMXBean
* MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
* NotificationEmitter emitter = (NotificationEmitter) mbean;
* MyListener listener = new MyListener();
* emitter.addNotificationListener(listener, null, null);
*
* // Assume this pool supports a usage threshold.
* // Set the threshold to myThreshold above which no new tasks
* // should be taken.
* pool.setUsageThreshold(myThreshold);
*
* // Usage threshold detection is enabled and notification will be
* // handled by MyListener. Continue for other processing.
* ....
*
* </pre>
* <hr>
* <p>
* There is no guarantee about when the <tt>MemoryMXBean</tt> will emit
* a threshold notification and when the notification will be delivered.
* When a notification listener is invoked, the memory usage of
* the memory pool may have crossed the usage threshold more
* than once.
* The {@link MemoryNotificationInfo#getCount} method returns the number
* of times that the memory usage has crossed the usage threshold
* at the point in time when the notification was constructed.
* It can be compared with the current usage threshold count returned
* by the {@link #getUsageThresholdCount} method to determine if
* such situation has occurred.
* </li>
* </ol>
*
* <h3><a name="CollectionThreshold">4. Collection Usage Threshold</a></h3>
*
* Collection usage threshold is a manageable attribute only applicable
* to some garbage-collected memory pools.
* After a Java virtual machine has expended effort in reclaiming memory
* space by recycling unused objects in a memory pool at garbage collection
* time, some number of bytes in the memory pools that are garbaged
* collected will still be in use. The collection usage threshold
* allows a value to be set for this number of bytes such
* that if the threshold is exceeded,
* a {@link MemoryNotificationInfo#MEMORY_THRESHOLD_EXCEEDED
* collection usage threshold exceeded notification}
* will be emitted by the {@link MemoryMXBean}.
* In addition, the {@link #getCollectionUsageThresholdCount
* collection usage threshold count} will then be incremented.
*
* <p>
* The {@link MemoryPoolMXBean#isCollectionUsageThresholdSupported} method can
* be used to determine if this functionality is supported.
*
* <p>
* A Java virtual machine performs collection usage threshold checking
* on a memory pool basis. This checking is enabled if the collection
* usage threshold is set to a positive value.
* If the collection usage threshold is set to zero, this checking
* is disabled on this memory pool. Default value is zero.
* The Java virtual machine performs the collection usage threshold
* checking at garbage collection time.
*
* <p>
* Some garbage-collected memory pools may
* choose not to support the collection usage threshold. For example,
* a memory pool is only managed by a continuous concurrent garbage
* collector. Objects can be allocated in this memory pool by some thread
* while the unused objects are reclaimed by the concurrent garbage
* collector simultaneously. Unless there is a well-defined
* garbage collection time which is the best appropriate time
* to check the memory usage, the collection usage threshold should not
* be supported.
*
* <p>
* The collection usage threshold is designed for monitoring the memory usage
* after the Java virtual machine has expended effort in reclaiming
* memory space. The collection usage could also be monitored
* by the polling and threshold notification mechanism
* described above for the <a href="#UsageThreshold">usage threshold</a>
* in a similar fashion.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a>
* @see <a href="package-summary.html#examples">
* Ways to Access MXBeans</a>
*
* @author Mandy Chung
* @since 1.5
*/
public interface MemoryPoolMXBean extends PlatformManagedObject {
/**
* Returns the name representing this memory pool.
*
* @return the name of this memory pool.
*/
public String getName();
/**
* Returns the type of this memory pool.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>MemoryType</tt> is <tt>String</tt>
* and the value is the name of the <tt>MemoryType</tt>.
*
* @return the type of this memory pool.
*/
public MemoryType getType();
/**
* Returns an estimate of the memory usage of this memory pool.
* This method returns <tt>null</tt>
* if this memory pool is not valid (i.e. no longer exists).
*
* <p>
* This method requests the Java virtual machine to make
* a best-effort estimate of the current memory usage of this
* memory pool. For some memory pools, this method may be an
* expensive operation that requires some computation to determine
* the estimate. An implementation should document when
* this is the case.
*
* <p>This method is designed for use in monitoring system
* memory usage and detecting low memory condition.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>MemoryUsage</tt> is
* <tt>CompositeData</tt> with attributes as specified in
* {@link MemoryUsage#from MemoryUsage}.
*
* @return a {@link MemoryUsage} object; or <tt>null</tt> if
* this pool not valid.
*/
public MemoryUsage getUsage();
/**
* Returns the peak memory usage of this memory pool since the
* Java virtual machine was started or since the peak was reset.
* This method returns <tt>null</tt>
* if this memory pool is not valid (i.e. no longer exists).
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>MemoryUsage</tt> is
* <tt>CompositeData</tt> with attributes as specified in
* {@link MemoryUsage#from MemoryUsage}.
*
* @return a {@link MemoryUsage} object representing the peak
* memory usage; or <tt>null</tt> if this pool is not valid.
*
*/
public MemoryUsage getPeakUsage();
/**
* Resets the peak memory usage statistic of this memory pool
* to the current memory usage.
*
* @throws java.lang.SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("control").
*/
public void resetPeakUsage();
/**
* Tests if this memory pool is valid in the Java virtual
* machine. A memory pool becomes invalid once the Java virtual
* machine removes it from the memory system.
*
* @return <tt>true</tt> if the memory pool is valid in the running
* Java virtual machine;
* <tt>false</tt> otherwise.
*/
public boolean isValid();
/**
* Returns the name of memory managers that manages this memory pool.
* Each memory pool will be managed by at least one memory manager.
*
* @return an array of <tt>String</tt> objects, each is the name of
* a memory manager managing this memory pool.
*/
public String[] getMemoryManagerNames();
/**
* Returns the usage threshold value of this memory pool in bytes.
* Each memory pool has a platform-dependent default threshold value.
* The current usage threshold can be changed via the
* {@link #setUsageThreshold setUsageThreshold} method.
*
* @return the usage threshold value of this memory pool in bytes.
*
* @throws UnsupportedOperationException if this memory pool
* does not support a usage threshold.
*
* @see #isUsageThresholdSupported
*/
public long getUsageThreshold();
/**
* Sets the threshold of this memory pool to the given <tt>threshold</tt>
* value if this memory pool supports the usage threshold.
* The usage threshold crossing checking is enabled in this memory pool
* if the threshold is set to a positive value.
* The usage threshold crossing checking is disabled
* if it is set to zero.
*
* @param threshold the new threshold value in bytes. Must be non-negative.
*
* @throws IllegalArgumentException if <tt>threshold</tt> is negative
* or greater than the maximum amount of memory for
* this memory pool if defined.
*
* @throws UnsupportedOperationException if this memory pool
* does not support a usage threshold.
*
* @throws java.lang.SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("control").
*
* @see #isUsageThresholdSupported
* @see <a href="#UsageThreshold">Usage threshold</a>
*/
public void setUsageThreshold(long threshold);
/**
* Tests if the memory usage of this memory pool
* reaches or exceeds its usage threshold value.
*
* @return <tt>true</tt> if the memory usage of
* this memory pool reaches or exceeds the threshold value;
* <tt>false</tt> otherwise.
*
* @throws UnsupportedOperationException if this memory pool
* does not support a usage threshold.
*/
public boolean isUsageThresholdExceeded();
/**
* Returns the number of times that the memory usage has crossed
* the usage threshold.
*
* @return the number of times that the memory usage
* has crossed its usage threshold value.
*
* @throws UnsupportedOperationException if this memory pool
* does not support a usage threshold.
*/
public long getUsageThresholdCount();
/**
* Tests if this memory pool supports usage threshold.
*
* @return <tt>true</tt> if this memory pool supports usage threshold;
* <tt>false</tt> otherwise.
*/
public boolean isUsageThresholdSupported();
/**
* Returns the collection usage threshold value of this memory pool
* in bytes. The default value is zero. The collection usage
* threshold can be changed via the
* {@link #setCollectionUsageThreshold setCollectionUsageThreshold} method.
*
* @return the collection usage threshold of this memory pool in bytes.
*
* @throws UnsupportedOperationException if this memory pool
* does not support a collection usage threshold.
*
* @see #isCollectionUsageThresholdSupported
*/
public long getCollectionUsageThreshold();
/**
* Sets the collection usage threshold of this memory pool to
* the given <tt>threshold</tt> value.
* When this threshold is set to positive, the Java virtual machine
* will check the memory usage at its best appropriate time after it has
* expended effort in recycling unused objects in this memory pool.
* <p>
* The collection usage threshold crossing checking is enabled
* in this memory pool if the threshold is set to a positive value.
* The collection usage threshold crossing checking is disabled
* if it is set to zero.
*
* @param threshold the new collection usage threshold value in bytes.
* Must be non-negative.
*
* @throws IllegalArgumentException if <tt>threshold</tt> is negative
* or greater than the maximum amount of memory for
* this memory pool if defined.
*
* @throws UnsupportedOperationException if this memory pool
* does not support a collection usage threshold.
*
* @throws java.lang.SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("control").
*
* @see #isCollectionUsageThresholdSupported
* @see <a href="#CollectionThreshold">Collection usage threshold</a>
*/
public void setCollectionUsageThreshold(long threshold);
/**
* Tests if the memory usage of this memory pool after
* the most recent collection on which the Java virtual
* machine has expended effort has reached or
* exceeded its collection usage threshold.
* This method does not request the Java virtual
* machine to perform any garbage collection other than its normal
* automatic memory management.
*
* @return <tt>true</tt> if the memory usage of this memory pool
* reaches or exceeds the collection usage threshold value
* in the most recent collection;
* <tt>false</tt> otherwise.
*
* @throws UnsupportedOperationException if this memory pool
* does not support a usage threshold.
*/
public boolean isCollectionUsageThresholdExceeded();
/**
* Returns the number of times that the Java virtual machine
* has detected that the memory usage has reached or
* exceeded the collection usage threshold.
*
* @return the number of times that the memory
* usage has reached or exceeded the collection usage threshold.
*
* @throws UnsupportedOperationException if this memory pool
* does not support a collection usage threshold.
*
* @see #isCollectionUsageThresholdSupported
*/
public long getCollectionUsageThresholdCount();
/**
* Returns the memory usage after the Java virtual machine
* most recently expended effort in recycling unused objects
* in this memory pool.
* This method does not request the Java virtual
* machine to perform any garbage collection other than its normal
* automatic memory management.
* This method returns <tt>null</tt> if the Java virtual
* machine does not support this method.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>MemoryUsage</tt> is
* <tt>CompositeData</tt> with attributes as specified in
* {@link MemoryUsage#from MemoryUsage}.
*
* @return a {@link MemoryUsage} representing the memory usage of
* this memory pool after the Java virtual machine most recently
* expended effort in recycling unused objects;
* <tt>null</tt> if this method is not supported.
*/
public MemoryUsage getCollectionUsage();
/**
* Tests if this memory pool supports a collection usage threshold.
*
* @return <tt>true</tt> if this memory pool supports the
* collection usage threshold; <tt>false</tt> otherwise.
*/
public boolean isCollectionUsageThresholdSupported();
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
/**
* Types of {@link MemoryPoolMXBean memory pools}.
*
* @author Mandy Chung
* @since 1.5
*/
public enum MemoryType {
/**
* Heap memory type.
* <p>
* The Java virtual machine has a <i>heap</i>
* that is the runtime data area from which
* memory for all class instances and arrays are allocated.
*/
HEAP("Heap memory"),
/**
* Non-heap memory type.
* <p>
* The Java virtual machine manages memory other than the heap
* (referred as <i>non-heap memory</i>). The non-heap memory includes
* the <i>method area</i> and memory required for the internal
* processing or optimization for the Java virtual machine.
* It stores per-class structures such as a runtime
* constant pool, field and method data, and the code for
* methods and constructors.
*/
NON_HEAP("Non-heap memory");
private final String description;
private MemoryType(String s) {
this.description = s;
}
/**
* Returns the string representation of this <tt>MemoryType</tt>.
* @return the string representation of this <tt>MemoryType</tt>.
*/
public String toString() {
return description;
}
private static final long serialVersionUID = 6992337162326171013L;
}

View File

@@ -0,0 +1,301 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
import javax.management.openmbean.CompositeData;
import sun.management.MemoryUsageCompositeData;
/**
* A <tt>MemoryUsage</tt> object represents a snapshot of memory usage.
* Instances of the <tt>MemoryUsage</tt> class are usually constructed
* by methods that are used to obtain memory usage
* information about individual memory pool of the Java virtual machine or
* the heap or non-heap memory of the Java virtual machine as a whole.
*
* <p> A <tt>MemoryUsage</tt> object contains four values:
* <table summary="Describes the MemoryUsage object content">
* <tr>
* <td valign=top> <tt>init</tt> </td>
* <td valign=top> represents the initial amount of memory (in bytes) that
* the Java virtual machine requests from the operating system
* for memory management during startup. The Java virtual machine
* may request additional memory from the operating system and
* may also release memory to the system over time.
* The value of <tt>init</tt> may be undefined.
* </td>
* </tr>
* <tr>
* <td valign=top> <tt>used</tt> </td>
* <td valign=top> represents the amount of memory currently used (in bytes).
* </td>
* </tr>
* <tr>
* <td valign=top> <tt>committed</tt> </td>
* <td valign=top> represents the amount of memory (in bytes) that is
* guaranteed to be available for use by the Java virtual machine.
* The amount of committed memory may change over time (increase
* or decrease). The Java virtual machine may release memory to
* the system and <tt>committed</tt> could be less than <tt>init</tt>.
* <tt>committed</tt> will always be greater than
* or equal to <tt>used</tt>.
* </td>
* </tr>
* <tr>
* <td valign=top> <tt>max</tt> </td>
* <td valign=top> represents the maximum amount of memory (in bytes)
* that can be used for memory management. Its value may be undefined.
* The maximum amount of memory may change over time if defined.
* The amount of used and committed memory will always be less than
* or equal to <tt>max</tt> if <tt>max</tt> is defined.
* A memory allocation may fail if it attempts to increase the
* used memory such that <tt>used &gt; committed</tt> even
* if <tt>used &lt;= max</tt> would still be true (for example,
* when the system is low on virtual memory).
* </td>
* </tr>
* </table>
*
* Below is a picture showing an example of a memory pool:
*
* <pre>
* +----------------------------------------------+
* +//////////////// | +
* +//////////////// | +
* +----------------------------------------------+
*
* |--------|
* init
* |---------------|
* used
* |---------------------------|
* committed
* |----------------------------------------------|
* max
* </pre>
*
* <h3>MXBean Mapping</h3>
* <tt>MemoryUsage</tt> is mapped to a {@link CompositeData CompositeData}
* with attributes as specified in the {@link #from from} method.
*
* @author Mandy Chung
* @since 1.5
*/
public class MemoryUsage {
private final long init;
private final long used;
private final long committed;
private final long max;
/**
* Constructs a <tt>MemoryUsage</tt> object.
*
* @param init the initial amount of memory in bytes that
* the Java virtual machine allocates;
* or <tt>-1</tt> if undefined.
* @param used the amount of used memory in bytes.
* @param committed the amount of committed memory in bytes.
* @param max the maximum amount of memory in bytes that
* can be used; or <tt>-1</tt> if undefined.
*
* @throws IllegalArgumentException if
* <ul>
* <li> the value of <tt>init</tt> or <tt>max</tt> is negative
* but not <tt>-1</tt>; or</li>
* <li> the value of <tt>used</tt> or <tt>committed</tt> is negative;
* or</li>
* <li> <tt>used</tt> is greater than the value of <tt>committed</tt>;
* or</li>
* <li> <tt>committed</tt> is greater than the value of <tt>max</tt>
* <tt>max</tt> if defined.</li>
* </ul>
*/
public MemoryUsage(long init,
long used,
long committed,
long max) {
if (init < -1) {
throw new IllegalArgumentException( "init parameter = " +
init + " is negative but not -1.");
}
if (max < -1) {
throw new IllegalArgumentException( "max parameter = " +
max + " is negative but not -1.");
}
if (used < 0) {
throw new IllegalArgumentException( "used parameter = " +
used + " is negative.");
}
if (committed < 0) {
throw new IllegalArgumentException( "committed parameter = " +
committed + " is negative.");
}
if (used > committed) {
throw new IllegalArgumentException( "used = " + used +
" should be <= committed = " + committed);
}
if (max >= 0 && committed > max) {
throw new IllegalArgumentException( "committed = " + committed +
" should be < max = " + max);
}
this.init = init;
this.used = used;
this.committed = committed;
this.max = max;
}
/**
* Constructs a <tt>MemoryUsage</tt> object from a
* {@link CompositeData CompositeData}.
*/
private MemoryUsage(CompositeData cd) {
// validate the input composite data
MemoryUsageCompositeData.validateCompositeData(cd);
this.init = MemoryUsageCompositeData.getInit(cd);
this.used = MemoryUsageCompositeData.getUsed(cd);
this.committed = MemoryUsageCompositeData.getCommitted(cd);
this.max = MemoryUsageCompositeData.getMax(cd);
}
/**
* Returns the amount of memory in bytes that the Java virtual machine
* initially requests from the operating system for memory management.
* This method returns <tt>-1</tt> if the initial memory size is undefined.
*
* @return the initial size of memory in bytes;
* <tt>-1</tt> if undefined.
*/
public long getInit() {
return init;
}
/**
* Returns the amount of used memory in bytes.
*
* @return the amount of used memory in bytes.
*
*/
public long getUsed() {
return used;
};
/**
* Returns the amount of memory in bytes that is committed for
* the Java virtual machine to use. This amount of memory is
* guaranteed for the Java virtual machine to use.
*
* @return the amount of committed memory in bytes.
*
*/
public long getCommitted() {
return committed;
};
/**
* Returns the maximum amount of memory in bytes that can be
* used for memory management. This method returns <tt>-1</tt>
* if the maximum memory size is undefined.
*
* <p> This amount of memory is not guaranteed to be available
* for memory management if it is greater than the amount of
* committed memory. The Java virtual machine may fail to allocate
* memory even if the amount of used memory does not exceed this
* maximum size.
*
* @return the maximum amount of memory in bytes;
* <tt>-1</tt> if undefined.
*/
public long getMax() {
return max;
};
/**
* Returns a descriptive representation of this memory usage.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("init = " + init + "(" + (init >> 10) + "K) ");
buf.append("used = " + used + "(" + (used >> 10) + "K) ");
buf.append("committed = " + committed + "(" +
(committed >> 10) + "K) " );
buf.append("max = " + max + "(" + (max >> 10) + "K)");
return buf.toString();
}
/**
* Returns a <tt>MemoryUsage</tt> object represented by the
* given <tt>CompositeData</tt>. The given <tt>CompositeData</tt>
* must contain the following attributes:
*
* <blockquote>
* <table border summary="The attributes and the types the given CompositeData contains">
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
* </tr>
* <tr>
* <td>init</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* <tr>
* <td>used</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* <tr>
* <td>committed</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* <tr>
* <td>max</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* </table>
* </blockquote>
*
* @param cd <tt>CompositeData</tt> representing a <tt>MemoryUsage</tt>
*
* @throws IllegalArgumentException if <tt>cd</tt> does not
* represent a <tt>MemoryUsage</tt> with the attributes described
* above.
*
* @return a <tt>MemoryUsage</tt> object represented by <tt>cd</tt>
* if <tt>cd</tt> is not <tt>null</tt>;
* <tt>null</tt> otherwise.
*/
public static MemoryUsage from(CompositeData cd) {
if (cd == null) {
return null;
}
if (cd instanceof MemoryUsageCompositeData) {
return ((MemoryUsageCompositeData) cd).getMemoryUsage();
} else {
return new MemoryUsage(cd);
}
}
}

View File

@@ -0,0 +1,159 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
import javax.management.openmbean.CompositeData;
import sun.management.MonitorInfoCompositeData;
/**
* Information about an object monitor lock. An object monitor is locked
* when entering a synchronization block or method on that object.
*
* <h3>MXBean Mapping</h3>
* <tt>MonitorInfo</tt> is mapped to a {@link CompositeData CompositeData}
* with attributes as specified in
* the {@link #from from} method.
*
* @author Mandy Chung
* @since 1.6
*/
public class MonitorInfo extends LockInfo {
private int stackDepth;
private StackTraceElement stackFrame;
/**
* Construct a <tt>MonitorInfo</tt> object.
*
* @param className the fully qualified name of the class of the lock object.
* @param identityHashCode the {@link System#identityHashCode
* identity hash code} of the lock object.
* @param stackDepth the depth in the stack trace where the object monitor
* was locked.
* @param stackFrame the stack frame that locked the object monitor.
* @throws IllegalArgumentException if
* <tt>stackDepth</tt> &ge; 0 but <tt>stackFrame</tt> is <tt>null</tt>,
* or <tt>stackDepth</tt> &lt; 0 but <tt>stackFrame</tt> is not
* <tt>null</tt>.
*/
public MonitorInfo(String className,
int identityHashCode,
int stackDepth,
StackTraceElement stackFrame) {
super(className, identityHashCode);
if (stackDepth >= 0 && stackFrame == null) {
throw new IllegalArgumentException("Parameter stackDepth is " +
stackDepth + " but stackFrame is null");
}
if (stackDepth < 0 && stackFrame != null) {
throw new IllegalArgumentException("Parameter stackDepth is " +
stackDepth + " but stackFrame is not null");
}
this.stackDepth = stackDepth;
this.stackFrame = stackFrame;
}
/**
* Returns the depth in the stack trace where the object monitor
* was locked. The depth is the index to the <tt>StackTraceElement</tt>
* array returned in the {@link ThreadInfo#getStackTrace} method.
*
* @return the depth in the stack trace where the object monitor
* was locked, or a negative number if not available.
*/
public int getLockedStackDepth() {
return stackDepth;
}
/**
* Returns the stack frame that locked the object monitor.
*
* @return <tt>StackTraceElement</tt> that locked the object monitor,
* or <tt>null</tt> if not available.
*/
public StackTraceElement getLockedStackFrame() {
return stackFrame;
}
/**
* Returns a <tt>MonitorInfo</tt> object represented by the
* given <tt>CompositeData</tt>.
* The given <tt>CompositeData</tt> must contain the following attributes
* as well as the attributes specified in the
* <a href="LockInfo.html#MappedType">
* mapped type</a> for the {@link LockInfo} class:
* <blockquote>
* <table border summary="The attributes and their types the given CompositeData contains">
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
* </tr>
* <tr>
* <td>lockedStackFrame</td>
* <td><tt>CompositeData as specified in the
* <a href="ThreadInfo.html#StackTrace">stackTrace</a>
* attribute defined in the {@link ThreadInfo#from
* ThreadInfo.from} method.
* </tt></td>
* </tr>
* <tr>
* <td>lockedStackDepth</td>
* <td><tt>java.lang.Integer</tt></td>
* </tr>
* </table>
* </blockquote>
*
* @param cd <tt>CompositeData</tt> representing a <tt>MonitorInfo</tt>
*
* @throws IllegalArgumentException if <tt>cd</tt> does not
* represent a <tt>MonitorInfo</tt> with the attributes described
* above.
* @return a <tt>MonitorInfo</tt> object represented
* by <tt>cd</tt> if <tt>cd</tt> is not <tt>null</tt>;
* <tt>null</tt> otherwise.
*/
public static MonitorInfo from(CompositeData cd) {
if (cd == null) {
return null;
}
if (cd instanceof MonitorInfoCompositeData) {
return ((MonitorInfoCompositeData) cd).getMonitorInfo();
} else {
MonitorInfoCompositeData.validateCompositeData(cd);
String className = MonitorInfoCompositeData.getClassName(cd);
int identityHashCode = MonitorInfoCompositeData.getIdentityHashCode(cd);
int stackDepth = MonitorInfoCompositeData.getLockedStackDepth(cd);
StackTraceElement stackFrame = MonitorInfoCompositeData.getLockedStackFrame(cd);
return new MonitorInfo(className,
identityHashCode,
stackDepth,
stackFrame);
}
}
}

View File

@@ -0,0 +1,142 @@
/*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
/**
* The management interface for the operating system on which
* the Java virtual machine is running.
*
* <p> A Java virtual machine has a single instance of the implementation
* class of this interface. This instance implementing this interface is
* an <a href="ManagementFactory.html#MXBean">MXBean</a>
* that can be obtained by calling
* the {@link ManagementFactory#getOperatingSystemMXBean} method or
* from the {@link ManagementFactory#getPlatformMBeanServer
* platform <tt>MBeanServer</tt>} method.
*
* <p>The <tt>ObjectName</tt> for uniquely identifying the MXBean for
* the operating system within an MBeanServer is:
* <blockquote>
* {@link ManagementFactory#OPERATING_SYSTEM_MXBEAN_NAME
* <tt>java.lang:type=OperatingSystem</tt>}
* </blockquote>
*
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <p> This interface defines several convenient methods for accessing
* system properties about the operating system on which the Java
* virtual machine is running.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a>
* @see <a href="package-summary.html#examples">
* Ways to Access MXBeans</a>
*
* @author Mandy Chung
* @since 1.5
*/
public interface OperatingSystemMXBean extends PlatformManagedObject {
/**
* Returns the operating system name.
* This method is equivalent to <tt>System.getProperty("os.name")</tt>.
*
* @return the operating system name.
*
* @throws java.lang.SecurityException
* if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to this system property.
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperty
*/
public String getName();
/**
* Returns the operating system architecture.
* This method is equivalent to <tt>System.getProperty("os.arch")</tt>.
*
* @return the operating system architecture.
*
* @throws java.lang.SecurityException
* if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to this system property.
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperty
*/
public String getArch();
/**
* Returns the operating system version.
* This method is equivalent to <tt>System.getProperty("os.version")</tt>.
*
* @return the operating system version.
*
* @throws java.lang.SecurityException
* if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to this system property.
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperty
*/
public String getVersion();
/**
* Returns the number of processors available to the Java virtual machine.
* This method is equivalent to the {@link Runtime#availableProcessors()}
* method.
* <p> This value may change during a particular invocation of
* the virtual machine.
*
* @return the number of processors available to the virtual
* machine; never smaller than one.
*/
public int getAvailableProcessors();
/**
* Returns the system load average for the last minute.
* The system load average is the sum of the number of runnable entities
* queued to the {@linkplain #getAvailableProcessors available processors}
* and the number of runnable entities running on the available processors
* averaged over a period of time.
* The way in which the load average is calculated is operating system
* specific but is typically a damped time-dependent average.
* <p>
* If the load average is not available, a negative value is returned.
* <p>
* This method is designed to provide a hint about the system load
* and may be queried frequently.
* The load average may be unavailable on some platform where it is
* expensive to implement this method.
*
* @return the system load average; or a negative value if not available.
*
* @since 1.6
*/
public double getSystemLoadAverage();
}

View File

@@ -0,0 +1,468 @@
/*
* Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import com.sun.management.HotSpotDiagnosticMXBean;
import com.sun.management.UnixOperatingSystemMXBean;
import sun.management.ManagementFactoryHelper;
import sun.management.Util;
/**
* This enum class defines the list of platform components
* that provides monitoring and management support.
* Each enum represents one MXBean interface. A MXBean
* instance could implement one or more MXBean interfaces.
*
* For example, com.sun.management.GarbageCollectorMXBean
* extends java.lang.management.GarbageCollectorMXBean
* and there is one set of garbage collection MXBean instances,
* each of which implements both c.s.m. and j.l.m. interfaces.
* There are two separate enums GARBAGE_COLLECTOR
* and SUN_GARBAGE_COLLECTOR so that ManagementFactory.getPlatformMXBeans(Class)
* will return the list of MXBeans of the specified type.
*
* To add a new MXBean interface for the Java platform,
* add a new enum constant and implement the MXBeanFetcher.
*/
enum PlatformComponent {
/**
* Class loading system of the Java virtual machine.
*/
CLASS_LOADING(
"java.lang.management.ClassLoadingMXBean",
"java.lang", "ClassLoading", defaultKeyProperties(),
true, // singleton
new MXBeanFetcher<ClassLoadingMXBean>() {
public List<ClassLoadingMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getClassLoadingMXBean());
}
}),
/**
* Compilation system of the Java virtual machine.
*/
COMPILATION(
"java.lang.management.CompilationMXBean",
"java.lang", "Compilation", defaultKeyProperties(),
true, // singleton
new MXBeanFetcher<CompilationMXBean>() {
public List<CompilationMXBean> getMXBeans() {
CompilationMXBean m = ManagementFactoryHelper.getCompilationMXBean();
if (m == null) {
return Collections.emptyList();
} else {
return Collections.singletonList(m);
}
}
}),
/**
* Memory system of the Java virtual machine.
*/
MEMORY(
"java.lang.management.MemoryMXBean",
"java.lang", "Memory", defaultKeyProperties(),
true, // singleton
new MXBeanFetcher<MemoryMXBean>() {
public List<MemoryMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getMemoryMXBean());
}
}),
/**
* Garbage Collector in the Java virtual machine.
*/
GARBAGE_COLLECTOR(
"java.lang.management.GarbageCollectorMXBean",
"java.lang", "GarbageCollector", keyProperties("name"),
false, // zero or more instances
new MXBeanFetcher<GarbageCollectorMXBean>() {
public List<GarbageCollectorMXBean> getMXBeans() {
return ManagementFactoryHelper.
getGarbageCollectorMXBeans();
}
}),
/**
* Memory manager in the Java virtual machine.
*/
MEMORY_MANAGER(
"java.lang.management.MemoryManagerMXBean",
"java.lang", "MemoryManager", keyProperties("name"),
false, // zero or more instances
new MXBeanFetcher<MemoryManagerMXBean>() {
public List<MemoryManagerMXBean> getMXBeans() {
return ManagementFactoryHelper.getMemoryManagerMXBeans();
}
},
GARBAGE_COLLECTOR),
/**
* Memory pool in the Java virtual machine.
*/
MEMORY_POOL(
"java.lang.management.MemoryPoolMXBean",
"java.lang", "MemoryPool", keyProperties("name"),
false, // zero or more instances
new MXBeanFetcher<MemoryPoolMXBean>() {
public List<MemoryPoolMXBean> getMXBeans() {
return ManagementFactoryHelper.getMemoryPoolMXBeans();
}
}),
/**
* Operating system on which the Java virtual machine is running
*/
OPERATING_SYSTEM(
"java.lang.management.OperatingSystemMXBean",
"java.lang", "OperatingSystem", defaultKeyProperties(),
true, // singleton
new MXBeanFetcher<OperatingSystemMXBean>() {
public List<OperatingSystemMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getOperatingSystemMXBean());
}
}),
/**
* Runtime system of the Java virtual machine.
*/
RUNTIME(
"java.lang.management.RuntimeMXBean",
"java.lang", "Runtime", defaultKeyProperties(),
true, // singleton
new MXBeanFetcher<RuntimeMXBean>() {
public List<RuntimeMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getRuntimeMXBean());
}
}),
/**
* Threading system of the Java virtual machine.
*/
THREADING(
"java.lang.management.ThreadMXBean",
"java.lang", "Threading", defaultKeyProperties(),
true, // singleton
new MXBeanFetcher<ThreadMXBean>() {
public List<ThreadMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getThreadMXBean());
}
}),
/**
* Logging facility.
*/
LOGGING(
"java.lang.management.PlatformLoggingMXBean",
"java.util.logging", "Logging", defaultKeyProperties(),
true, // singleton
new MXBeanFetcher<PlatformLoggingMXBean>() {
public List<PlatformLoggingMXBean> getMXBeans() {
PlatformLoggingMXBean m = ManagementFactoryHelper.getPlatformLoggingMXBean();
if (m == null) {
return Collections.emptyList();
} else {
return Collections.singletonList(m);
}
}
}),
/**
* Buffer pools.
*/
BUFFER_POOL(
"java.lang.management.BufferPoolMXBean",
"java.nio", "BufferPool", keyProperties("name"),
false, // zero or more instances
new MXBeanFetcher<BufferPoolMXBean>() {
public List<BufferPoolMXBean> getMXBeans() {
return ManagementFactoryHelper.getBufferPoolMXBeans();
}
}),
// Sun Platform Extension
/**
* Sun extension garbage collector that performs collections in cycles.
*/
SUN_GARBAGE_COLLECTOR(
"com.sun.management.GarbageCollectorMXBean",
"java.lang", "GarbageCollector", keyProperties("name"),
false, // zero or more instances
new MXBeanFetcher<com.sun.management.GarbageCollectorMXBean>() {
public List<com.sun.management.GarbageCollectorMXBean> getMXBeans() {
return getGcMXBeanList(com.sun.management.GarbageCollectorMXBean.class);
}
}),
/**
* Sun extension operating system on which the Java virtual machine
* is running.
*/
SUN_OPERATING_SYSTEM(
"com.sun.management.OperatingSystemMXBean",
"java.lang", "OperatingSystem", defaultKeyProperties(),
true, // singleton
new MXBeanFetcher<com.sun.management.OperatingSystemMXBean>() {
public List<com.sun.management.OperatingSystemMXBean> getMXBeans() {
return getOSMXBeanList(com.sun.management.OperatingSystemMXBean.class);
}
}),
/**
* Unix operating system.
*/
SUN_UNIX_OPERATING_SYSTEM(
"com.sun.management.UnixOperatingSystemMXBean",
"java.lang", "OperatingSystem", defaultKeyProperties(),
true, // singleton
new MXBeanFetcher<UnixOperatingSystemMXBean>() {
public List<UnixOperatingSystemMXBean> getMXBeans() {
return getOSMXBeanList(com.sun.management.UnixOperatingSystemMXBean.class);
}
}),
/**
* Diagnostic support for the HotSpot Virtual Machine.
*/
HOTSPOT_DIAGNOSTIC(
"com.sun.management.HotSpotDiagnosticMXBean",
"com.sun.management", "HotSpotDiagnostic", defaultKeyProperties(),
true, // singleton
new MXBeanFetcher<HotSpotDiagnosticMXBean>() {
public List<HotSpotDiagnosticMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getDiagnosticMXBean());
}
});
/**
* A task that returns the MXBeans for a component.
*/
interface MXBeanFetcher<T extends PlatformManagedObject> {
public List<T> getMXBeans();
}
/*
* Returns a list of the GC MXBeans of the given type.
*/
private static <T extends GarbageCollectorMXBean>
List<T> getGcMXBeanList(Class<T> gcMXBeanIntf) {
List<GarbageCollectorMXBean> list =
ManagementFactoryHelper.getGarbageCollectorMXBeans();
List<T> result = new ArrayList<>(list.size());
for (GarbageCollectorMXBean m : list) {
if (gcMXBeanIntf.isInstance(m)) {
result.add(gcMXBeanIntf.cast(m));
}
}
return result;
}
/*
* Returns the OS mxbean instance of the given type.
*/
private static <T extends OperatingSystemMXBean>
List<T> getOSMXBeanList(Class<T> osMXBeanIntf) {
OperatingSystemMXBean m =
ManagementFactoryHelper.getOperatingSystemMXBean();
if (osMXBeanIntf.isInstance(m)) {
return Collections.singletonList(osMXBeanIntf.cast(m));
} else {
return Collections.emptyList();
}
}
private final String mxbeanInterfaceName;
private final String domain;
private final String type;
private final Set<String> keyProperties;
private final MXBeanFetcher<?> fetcher;
private final PlatformComponent[] subComponents;
private final boolean singleton;
private PlatformComponent(String intfName,
String domain, String type,
Set<String> keyProperties,
boolean singleton,
MXBeanFetcher<?> fetcher,
PlatformComponent... subComponents) {
this.mxbeanInterfaceName = intfName;
this.domain = domain;
this.type = type;
this.keyProperties = keyProperties;
this.singleton = singleton;
this.fetcher = fetcher;
this.subComponents = subComponents;
}
private static Set<String> defaultKeyProps;
private static Set<String> defaultKeyProperties() {
if (defaultKeyProps == null) {
defaultKeyProps = Collections.singleton("type");
}
return defaultKeyProps;
}
private static Set<String> keyProperties(String... keyNames) {
Set<String> set = new HashSet<>();
set.add("type");
for (String s : keyNames) {
set.add(s);
}
return set;
}
boolean isSingleton() {
return singleton;
}
String getMXBeanInterfaceName() {
return mxbeanInterfaceName;
}
@SuppressWarnings("unchecked")
Class<? extends PlatformManagedObject> getMXBeanInterface() {
try {
// Lazy loading the MXBean interface only when it is needed
return (Class<? extends PlatformManagedObject>)
Class.forName(mxbeanInterfaceName, false,
PlatformManagedObject.class.getClassLoader());
} catch (ClassNotFoundException x) {
throw new AssertionError(x);
}
}
@SuppressWarnings("unchecked")
<T extends PlatformManagedObject>
List<T> getMXBeans(Class<T> mxbeanInterface)
{
return (List<T>) fetcher.getMXBeans();
}
<T extends PlatformManagedObject> T getSingletonMXBean(Class<T> mxbeanInterface)
{
if (!singleton)
throw new IllegalArgumentException(mxbeanInterfaceName +
" can have zero or more than one instances");
List<T> list = getMXBeans(mxbeanInterface);
assert list.size() == 1;
return list.isEmpty() ? null : list.get(0);
}
<T extends PlatformManagedObject>
T getSingletonMXBean(MBeanServerConnection mbs, Class<T> mxbeanInterface)
throws java.io.IOException
{
if (!singleton)
throw new IllegalArgumentException(mxbeanInterfaceName +
" can have zero or more than one instances");
// ObjectName of a singleton MXBean contains only domain and type
assert keyProperties.size() == 1;
String on = domain + ":type=" + type;
return ManagementFactory.newPlatformMXBeanProxy(mbs,
on,
mxbeanInterface);
}
<T extends PlatformManagedObject>
List<T> getMXBeans(MBeanServerConnection mbs, Class<T> mxbeanInterface)
throws java.io.IOException
{
List<T> result = new ArrayList<>();
for (ObjectName on : getObjectNames(mbs)) {
result.add(ManagementFactory.
newPlatformMXBeanProxy(mbs,
on.getCanonicalName(),
mxbeanInterface)
);
}
return result;
}
private Set<ObjectName> getObjectNames(MBeanServerConnection mbs)
throws java.io.IOException
{
String domainAndType = domain + ":type=" + type;
if (keyProperties.size() > 1) {
// if there are more than 1 key properties (i.e. other than "type")
domainAndType += ",*";
}
ObjectName on = Util.newObjectName(domainAndType);
Set<ObjectName> set = mbs.queryNames(on, null);
for (PlatformComponent pc : subComponents) {
set.addAll(pc.getObjectNames(mbs));
}
return set;
}
// a map from MXBean interface name to PlatformComponent
private static Map<String, PlatformComponent> enumMap;
private static synchronized void ensureInitialized() {
if (enumMap == null) {
enumMap = new HashMap<>();
for (PlatformComponent pc: PlatformComponent.values()) {
// Use String as the key rather than Class<?> to avoid
// causing unnecessary class loading of management interface
enumMap.put(pc.getMXBeanInterfaceName(), pc);
}
}
}
static boolean isPlatformMXBean(String cn) {
ensureInitialized();
return enumMap.containsKey(cn);
}
static <T extends PlatformManagedObject>
PlatformComponent getPlatformComponent(Class<T> mxbeanInterface)
{
ensureInitialized();
String cn = mxbeanInterface.getName();
PlatformComponent pc = enumMap.get(cn);
if (pc != null && pc.getMXBeanInterface() == mxbeanInterface)
return pc;
return null;
}
private static final long serialVersionUID = 6992337162326171013L;
}

View File

@@ -0,0 +1,138 @@
/*
* Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
/**
* The management interface for the {@linkplain java.util.logging logging} facility.
*
* <p>There is a single global instance of the <tt>PlatformLoggingMXBean</tt>.
* The {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
* ManagementFactory.getPlatformMXBean} method can be used to obtain
* the {@code PlatformLoggingMXBean} object as follows:
* <pre>
* PlatformLoggingMXBean logging = ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class);
* </pre>
* The {@code PlatformLoggingMXBean} object is also registered with the
* platform {@linkplain java.lang.management.ManagementFactory#getPlatformMBeanServer
* MBeanServer}.
* The {@link javax.management.ObjectName ObjectName} for uniquely
* identifying the {@code PlatformLoggingMXBean} within an MBeanServer is:
* <pre>
* {@link java.util.logging.LogManager#LOGGING_MXBEAN_NAME java.util.logging:type=Logging}
* </pre>
*
* <p>The instance registered in the platform <tt>MBeanServer</tt> with
* this {@code ObjectName} implements all attributes defined by
* {@link java.util.logging.LoggingMXBean}.
*
* @since 1.7
*/
public interface PlatformLoggingMXBean extends PlatformManagedObject {
/**
* Returns the list of the currently registered
* {@linkplain java.util.logging.Logger logger} names. This method
* calls {@link java.util.logging.LogManager#getLoggerNames} and
* returns a list of the logger names.
*
* @return A list of {@code String} each of which is a
* currently registered {@code Logger} name.
*/
java.util.List<String> getLoggerNames();
/**
* Gets the name of the log {@linkplain java.util.logging.Logger#getLevel
* level} associated with the specified logger.
* If the specified logger does not exist, {@code null}
* is returned.
* This method first finds the logger of the given name and
* then returns the name of the log level by calling:
* <blockquote>
* {@link java.util.logging.Logger#getLevel
* Logger.getLevel()}.{@link java.util.logging.Level#getName getName()};
* </blockquote>
*
* <p>
* If the {@code Level} of the specified logger is {@code null},
* which means that this logger's effective level is inherited
* from its parent, an empty string will be returned.
*
* @param loggerName The name of the {@code Logger} to be retrieved.
*
* @return The name of the log level of the specified logger; or
* an empty string if the log level of the specified logger
* is {@code null}. If the specified logger does not
* exist, {@code null} is returned.
*
* @see java.util.logging.Logger#getLevel
*/
String getLoggerLevel(String loggerName);
/**
* Sets the specified logger to the specified new
* {@linkplain java.util.logging.Logger#setLevel level}.
* If the {@code levelName} is not {@code null}, the level
* of the specified logger is set to the parsed
* {@link java.util.logging.Level Level}
* matching the {@code levelName}.
* If the {@code levelName} is {@code null}, the level
* of the specified logger is set to {@code null} and
* the effective level of the logger is inherited from
* its nearest ancestor with a specific (non-null) level value.
*
* @param loggerName The name of the {@code Logger} to be set.
* Must be non-null.
* @param levelName The name of the level to set on the specified logger,
* or {@code null} if setting the level to inherit
* from its nearest ancestor.
*
* @throws IllegalArgumentException if the specified logger
* does not exist, or {@code levelName} is not a valid level name.
*
* @throws SecurityException if a security manager exists and if
* the caller does not have LoggingPermission("control").
*
* @see java.util.logging.Logger#setLevel
*/
void setLoggerLevel(String loggerName, String levelName);
/**
* Returns the name of the
* {@linkplain java.util.logging.Logger#getParent parent}
* for the specified logger.
* If the specified logger does not exist, {@code null} is returned.
* If the specified logger is the root {@code Logger} in the namespace,
* the result will be an empty string.
*
* @param loggerName The name of a {@code Logger}.
*
* @return the name of the nearest existing parent logger;
* an empty string if the specified logger is the root logger.
* If the specified logger does not exist, {@code null}
* is returned.
*/
String getParentLoggerName(String loggerName);
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
import javax.management.ObjectName;
/**
* A platform managed object is a {@linkplain javax.management.MXBean JMX MXBean}
* for monitoring and managing a component in the Java platform.
* Each platform managed object has a unique
* <a href="ManagementFactory.html#MXBean">object name</a>
* for the {@linkplain ManagementFactory#getPlatformMBeanServer
* platform MBeanServer} access.
* All platform MXBeans will implement this interface.
*
* <p>
* Note:
* The platform MXBean interfaces (i.e. all subinterfaces
* of {@code PlatformManagedObject}) are implemented
* by the Java platform only. New methods may be added in these interfaces
* in future Java SE releases.
* In addition, this {@code PlatformManagedObject} interface is only
* intended for the management interfaces for the platform to extend but
* not for applications.
*
* @see ManagementFactory
* @since 1.7
*/
public interface PlatformManagedObject {
/**
* Returns an {@link ObjectName ObjectName} instance representing
* the object name of this platform managed object.
*
* @return an {@link ObjectName ObjectName} instance representing
* the object name of this platform managed object.
*/
public ObjectName getObjectName();
}

View File

@@ -0,0 +1,339 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
/**
* The management interface for the runtime system of
* the Java virtual machine.
*
* <p> A Java virtual machine has a single instance of the implementation
* class of this interface. This instance implementing this interface is
* an <a href="ManagementFactory.html#MXBean">MXBean</a>
* that can be obtained by calling
* the {@link ManagementFactory#getRuntimeMXBean} method or
* from the {@link ManagementFactory#getPlatformMBeanServer
* platform <tt>MBeanServer</tt>} method.
*
* <p>The <tt>ObjectName</tt> for uniquely identifying the MXBean for
* the runtime system within an MBeanServer is:
* <blockquote>
* {@link ManagementFactory#RUNTIME_MXBEAN_NAME
* <tt>java.lang:type=Runtime</tt>}
* </blockquote>
*
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <p> This interface defines several convenient methods for accessing
* system properties about the Java virtual machine.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a>
* @see <a href="package-summary.html#examples">
* Ways to Access MXBeans</a>
*
* @author Mandy Chung
* @since 1.5
*/
public interface RuntimeMXBean extends PlatformManagedObject {
/**
* Returns the name representing the running Java virtual machine.
* The returned name string can be any arbitrary string and
* a Java virtual machine implementation can choose
* to embed platform-specific useful information in the
* returned name string. Each running virtual machine could have
* a different name.
*
* @return the name representing the running Java virtual machine.
*/
public String getName();
/**
* Returns the Java virtual machine implementation name.
* This method is equivalent to {@link System#getProperty
* System.getProperty("java.vm.name")}.
*
* @return the Java virtual machine implementation name.
*
* @throws java.lang.SecurityException
* if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to this system property.
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperty
*/
public String getVmName();
/**
* Returns the Java virtual machine implementation vendor.
* This method is equivalent to {@link System#getProperty
* System.getProperty("java.vm.vendor")}.
*
* @return the Java virtual machine implementation vendor.
*
* @throws java.lang.SecurityException
* if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to this system property.
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperty
*/
public String getVmVendor();
/**
* Returns the Java virtual machine implementation version.
* This method is equivalent to {@link System#getProperty
* System.getProperty("java.vm.version")}.
*
* @return the Java virtual machine implementation version.
*
* @throws java.lang.SecurityException
* if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to this system property.
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperty
*/
public String getVmVersion();
/**
* Returns the Java virtual machine specification name.
* This method is equivalent to {@link System#getProperty
* System.getProperty("java.vm.specification.name")}.
*
* @return the Java virtual machine specification name.
*
* @throws java.lang.SecurityException
* if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to this system property.
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperty
*/
public String getSpecName();
/**
* Returns the Java virtual machine specification vendor.
* This method is equivalent to {@link System#getProperty
* System.getProperty("java.vm.specification.vendor")}.
*
* @return the Java virtual machine specification vendor.
*
* @throws java.lang.SecurityException
* if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to this system property.
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperty
*/
public String getSpecVendor();
/**
* Returns the Java virtual machine specification version.
* This method is equivalent to {@link System#getProperty
* System.getProperty("java.vm.specification.version")}.
*
* @return the Java virtual machine specification version.
*
* @throws java.lang.SecurityException
* if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to this system property.
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperty
*/
public String getSpecVersion();
/**
* Returns the version of the specification for the management interface
* implemented by the running Java virtual machine.
*
* @return the version of the specification for the management interface
* implemented by the running Java virtual machine.
*/
public String getManagementSpecVersion();
/**
* Returns the Java class path that is used by the system class loader
* to search for class files.
* This method is equivalent to {@link System#getProperty
* System.getProperty("java.class.path")}.
*
* <p> Multiple paths in the Java class path are separated by the
* path separator character of the platform of the Java virtual machine
* being monitored.
*
* @return the Java class path.
*
* @throws java.lang.SecurityException
* if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to this system property.
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperty
*/
public String getClassPath();
/**
* Returns the Java library path.
* This method is equivalent to {@link System#getProperty
* System.getProperty("java.library.path")}.
*
* <p> Multiple paths in the Java library path are separated by the
* path separator character of the platform of the Java virtual machine
* being monitored.
*
* @return the Java library path.
*
* @throws java.lang.SecurityException
* if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to this system property.
* @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
* @see java.lang.System#getProperty
*/
public String getLibraryPath();
/**
* Tests if the Java virtual machine supports the boot class path
* mechanism used by the bootstrap class loader to search for class
* files.
*
* @return <tt>true</tt> if the Java virtual machine supports the
* class path mechanism; <tt>false</tt> otherwise.
*/
public boolean isBootClassPathSupported();
/**
* Returns the boot class path that is used by the bootstrap class loader
* to search for class files.
*
* <p> Multiple paths in the boot class path are separated by the
* path separator character of the platform on which the Java
* virtual machine is running.
*
* <p>A Java virtual machine implementation may not support
* the boot class path mechanism for the bootstrap class loader
* to search for class files.
* The {@link #isBootClassPathSupported} method can be used
* to determine if the Java virtual machine supports this method.
*
* @return the boot class path.
*
* @throws java.lang.UnsupportedOperationException
* if the Java virtual machine does not support this operation.
*
* @throws java.lang.SecurityException
* if a security manager exists and the caller does not have
* ManagementPermission("monitor").
*/
public String getBootClassPath();
/**
* Returns the input arguments passed to the Java virtual machine
* which does not include the arguments to the <tt>main</tt> method.
* This method returns an empty list if there is no input argument
* to the Java virtual machine.
* <p>
* Some Java virtual machine implementations may take input arguments
* from multiple different sources: for examples, arguments passed from
* the application that launches the Java virtual machine such as
* the 'java' command, environment variables, configuration files, etc.
* <p>
* Typically, not all command-line options to the 'java' command
* are passed to the Java virtual machine.
* Thus, the returned input arguments may not
* include all command-line options.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of {@code List<String>} is <tt>String[]</tt>.
*
* @return a list of <tt>String</tt> objects; each element
* is an argument passed to the Java virtual machine.
*
* @throws java.lang.SecurityException
* if a security manager exists and the caller does not have
* ManagementPermission("monitor").
*/
public java.util.List<String> getInputArguments();
/**
* Returns the uptime of the Java virtual machine in milliseconds.
*
* @return uptime of the Java virtual machine in milliseconds.
*/
public long getUptime();
/**
* Returns the start time of the Java virtual machine in milliseconds.
* This method returns the approximate time when the Java virtual
* machine started.
*
* @return start time of the Java virtual machine in milliseconds.
*
*/
public long getStartTime();
/**
* Returns a map of names and values of all system properties.
* This method calls {@link System#getProperties} to get all
* system properties. Properties whose name or value is not
* a <tt>String</tt> are omitted.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of {@code Map<String,String>} is
* {@link javax.management.openmbean.TabularData TabularData}
* with two items in each row as follows:
* <blockquote>
* <table border summary="Name and Type for each item">
* <tr>
* <th>Item Name</th>
* <th>Item Type</th>
* </tr>
* <tr>
* <td><tt>key</tt></td>
* <td><tt>String</tt></td>
* </tr>
* <tr>
* <td><tt>value</tt></td>
* <td><tt>String</tt></td>
* </tr>
* </table>
* </blockquote>
*
* @return a map of names and values of all system properties.
*
* @throws java.lang.SecurityException
* if a security manager exists and its
* <code>checkPropertiesAccess</code> method doesn't allow access
* to the system properties.
*/
public java.util.Map<String, String> getSystemProperties();
}

View File

@@ -0,0 +1,834 @@
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
import javax.management.openmbean.CompositeData;
import sun.management.ManagementFactoryHelper;
import sun.management.ThreadInfoCompositeData;
import static java.lang.Thread.State.*;
/**
* Thread information. <tt>ThreadInfo</tt> contains the information
* about a thread including:
* <h3>General thread information</h3>
* <ul>
* <li>Thread ID.</li>
* <li>Name of the thread.</li>
* </ul>
*
* <h3>Execution information</h3>
* <ul>
* <li>Thread state.</li>
* <li>The object upon which the thread is blocked due to:
* <ul>
* <li>waiting to enter a synchronization block/method, or</li>
* <li>waiting to be notified in a {@link Object#wait Object.wait} method,
* or</li>
* <li>parking due to a {@link java.util.concurrent.locks.LockSupport#park
* LockSupport.park} call.</li>
* </ul>
* </li>
* <li>The ID of the thread that owns the object
* that the thread is blocked.</li>
* <li>Stack trace of the thread.</li>
* <li>List of object monitors locked by the thread.</li>
* <li>List of <a href="LockInfo.html#OwnableSynchronizer">
* ownable synchronizers</a> locked by the thread.</li>
* </ul>
*
* <h4><a name="SyncStats">Synchronization Statistics</a></h4>
* <ul>
* <li>The number of times that the thread has blocked for
* synchronization or waited for notification.</li>
* <li>The accumulated elapsed time that the thread has blocked
* for synchronization or waited for notification
* since {@link ThreadMXBean#setThreadContentionMonitoringEnabled
* thread contention monitoring}
* was enabled. Some Java virtual machine implementation
* may not support this. The
* {@link ThreadMXBean#isThreadContentionMonitoringSupported()}
* method can be used to determine if a Java virtual machine
* supports this.</li>
* </ul>
*
* <p>This thread information class is designed for use in monitoring of
* the system, not for synchronization control.
*
* <h4>MXBean Mapping</h4>
* <tt>ThreadInfo</tt> is mapped to a {@link CompositeData CompositeData}
* with attributes as specified in
* the {@link #from from} method.
*
* @see ThreadMXBean#getThreadInfo
* @see ThreadMXBean#dumpAllThreads
*
* @author Mandy Chung
* @since 1.5
*/
public class ThreadInfo {
private String threadName;
private long threadId;
private long blockedTime;
private long blockedCount;
private long waitedTime;
private long waitedCount;
private LockInfo lock;
private String lockName;
private long lockOwnerId;
private String lockOwnerName;
private boolean inNative;
private boolean suspended;
private Thread.State threadState;
private StackTraceElement[] stackTrace;
private MonitorInfo[] lockedMonitors;
private LockInfo[] lockedSynchronizers;
private static MonitorInfo[] EMPTY_MONITORS = new MonitorInfo[0];
private static LockInfo[] EMPTY_SYNCS = new LockInfo[0];
/**
* Constructor of ThreadInfo created by the JVM
*
* @param t Thread
* @param state Thread state
* @param lockObj Object on which the thread is blocked
* @param lockOwner the thread holding the lock
* @param blockedCount Number of times blocked to enter a lock
* @param blockedTime Approx time blocked to enter a lock
* @param waitedCount Number of times waited on a lock
* @param waitedTime Approx time waited on a lock
* @param stackTrace Thread stack trace
*/
private ThreadInfo(Thread t, int state, Object lockObj, Thread lockOwner,
long blockedCount, long blockedTime,
long waitedCount, long waitedTime,
StackTraceElement[] stackTrace) {
initialize(t, state, lockObj, lockOwner,
blockedCount, blockedTime,
waitedCount, waitedTime, stackTrace,
EMPTY_MONITORS, EMPTY_SYNCS);
}
/**
* Constructor of ThreadInfo created by the JVM
* for {@link ThreadMXBean#getThreadInfo(long[],boolean,boolean)}
* and {@link ThreadMXBean#dumpAllThreads}
*
* @param t Thread
* @param state Thread state
* @param lockObj Object on which the thread is blocked
* @param lockOwner the thread holding the lock
* @param blockedCount Number of times blocked to enter a lock
* @param blockedTime Approx time blocked to enter a lock
* @param waitedCount Number of times waited on a lock
* @param waitedTime Approx time waited on a lock
* @param stackTrace Thread stack trace
* @param monitors List of locked monitors
* @param stackDepths List of stack depths
* @param synchronizers List of locked synchronizers
*/
private ThreadInfo(Thread t, int state, Object lockObj, Thread lockOwner,
long blockedCount, long blockedTime,
long waitedCount, long waitedTime,
StackTraceElement[] stackTrace,
Object[] monitors,
int[] stackDepths,
Object[] synchronizers) {
int numMonitors = (monitors == null ? 0 : monitors.length);
MonitorInfo[] lockedMonitors;
if (numMonitors == 0) {
lockedMonitors = EMPTY_MONITORS;
} else {
lockedMonitors = new MonitorInfo[numMonitors];
for (int i = 0; i < numMonitors; i++) {
Object lock = monitors[i];
String className = lock.getClass().getName();
int identityHashCode = System.identityHashCode(lock);
int depth = stackDepths[i];
StackTraceElement ste = (depth >= 0 ? stackTrace[depth]
: null);
lockedMonitors[i] = new MonitorInfo(className,
identityHashCode,
depth,
ste);
}
}
int numSyncs = (synchronizers == null ? 0 : synchronizers.length);
LockInfo[] lockedSynchronizers;
if (numSyncs == 0) {
lockedSynchronizers = EMPTY_SYNCS;
} else {
lockedSynchronizers = new LockInfo[numSyncs];
for (int i = 0; i < numSyncs; i++) {
Object lock = synchronizers[i];
String className = lock.getClass().getName();
int identityHashCode = System.identityHashCode(lock);
lockedSynchronizers[i] = new LockInfo(className,
identityHashCode);
}
}
initialize(t, state, lockObj, lockOwner,
blockedCount, blockedTime,
waitedCount, waitedTime, stackTrace,
lockedMonitors, lockedSynchronizers);
}
/**
* Initialize ThreadInfo object
*
* @param t Thread
* @param state Thread state
* @param lockObj Object on which the thread is blocked
* @param lockOwner the thread holding the lock
* @param blockedCount Number of times blocked to enter a lock
* @param blockedTime Approx time blocked to enter a lock
* @param waitedCount Number of times waited on a lock
* @param waitedTime Approx time waited on a lock
* @param stackTrace Thread stack trace
* @param lockedMonitors List of locked monitors
* @param lockedSynchronizers List of locked synchronizers
*/
private void initialize(Thread t, int state, Object lockObj, Thread lockOwner,
long blockedCount, long blockedTime,
long waitedCount, long waitedTime,
StackTraceElement[] stackTrace,
MonitorInfo[] lockedMonitors,
LockInfo[] lockedSynchronizers) {
this.threadId = t.getId();
this.threadName = t.getName();
this.threadState = ManagementFactoryHelper.toThreadState(state);
this.suspended = ManagementFactoryHelper.isThreadSuspended(state);
this.inNative = ManagementFactoryHelper.isThreadRunningNative(state);
this.blockedCount = blockedCount;
this.blockedTime = blockedTime;
this.waitedCount = waitedCount;
this.waitedTime = waitedTime;
if (lockObj == null) {
this.lock = null;
this.lockName = null;
} else {
this.lock = new LockInfo(lockObj);
this.lockName =
lock.getClassName() + '@' +
Integer.toHexString(lock.getIdentityHashCode());
}
if (lockOwner == null) {
this.lockOwnerId = -1;
this.lockOwnerName = null;
} else {
this.lockOwnerId = lockOwner.getId();
this.lockOwnerName = lockOwner.getName();
}
if (stackTrace == null) {
this.stackTrace = NO_STACK_TRACE;
} else {
this.stackTrace = stackTrace;
}
this.lockedMonitors = lockedMonitors;
this.lockedSynchronizers = lockedSynchronizers;
}
/*
* Constructs a <tt>ThreadInfo</tt> object from a
* {@link CompositeData CompositeData}.
*/
private ThreadInfo(CompositeData cd) {
ThreadInfoCompositeData ticd = ThreadInfoCompositeData.getInstance(cd);
threadId = ticd.threadId();
threadName = ticd.threadName();
blockedTime = ticd.blockedTime();
blockedCount = ticd.blockedCount();
waitedTime = ticd.waitedTime();
waitedCount = ticd.waitedCount();
lockName = ticd.lockName();
lockOwnerId = ticd.lockOwnerId();
lockOwnerName = ticd.lockOwnerName();
threadState = ticd.threadState();
suspended = ticd.suspended();
inNative = ticd.inNative();
stackTrace = ticd.stackTrace();
// 6.0 attributes
if (ticd.isCurrentVersion()) {
lock = ticd.lockInfo();
lockedMonitors = ticd.lockedMonitors();
lockedSynchronizers = ticd.lockedSynchronizers();
} else {
// lockInfo is a new attribute added in 1.6 ThreadInfo
// If cd is a 5.0 version, construct the LockInfo object
// from the lockName value.
if (lockName != null) {
String result[] = lockName.split("@");
if (result.length == 2) {
int identityHashCode = Integer.parseInt(result[1], 16);
lock = new LockInfo(result[0], identityHashCode);
} else {
assert result.length == 2;
lock = null;
}
} else {
lock = null;
}
lockedMonitors = EMPTY_MONITORS;
lockedSynchronizers = EMPTY_SYNCS;
}
}
/**
* Returns the ID of the thread associated with this <tt>ThreadInfo</tt>.
*
* @return the ID of the associated thread.
*/
public long getThreadId() {
return threadId;
}
/**
* Returns the name of the thread associated with this <tt>ThreadInfo</tt>.
*
* @return the name of the associated thread.
*/
public String getThreadName() {
return threadName;
}
/**
* Returns the state of the thread associated with this <tt>ThreadInfo</tt>.
*
* @return <tt>Thread.State</tt> of the associated thread.
*/
public Thread.State getThreadState() {
return threadState;
}
/**
* Returns the approximate accumulated elapsed time (in milliseconds)
* that the thread associated with this <tt>ThreadInfo</tt>
* has blocked to enter or reenter a monitor
* since thread contention monitoring is enabled.
* I.e. the total accumulated time the thread has been in the
* {@link java.lang.Thread.State#BLOCKED BLOCKED} state since thread
* contention monitoring was last enabled.
* This method returns <tt>-1</tt> if thread contention monitoring
* is disabled.
*
* <p>The Java virtual machine may measure the time with a high
* resolution timer. This statistic is reset when
* the thread contention monitoring is reenabled.
*
* @return the approximate accumulated elapsed time in milliseconds
* that a thread entered the <tt>BLOCKED</tt> state;
* <tt>-1</tt> if thread contention monitoring is disabled.
*
* @throws java.lang.UnsupportedOperationException if the Java
* virtual machine does not support this operation.
*
* @see ThreadMXBean#isThreadContentionMonitoringSupported
* @see ThreadMXBean#setThreadContentionMonitoringEnabled
*/
public long getBlockedTime() {
return blockedTime;
}
/**
* Returns the total number of times that
* the thread associated with this <tt>ThreadInfo</tt>
* blocked to enter or reenter a monitor.
* I.e. the number of times a thread has been in the
* {@link java.lang.Thread.State#BLOCKED BLOCKED} state.
*
* @return the total number of times that the thread
* entered the <tt>BLOCKED</tt> state.
*/
public long getBlockedCount() {
return blockedCount;
}
/**
* Returns the approximate accumulated elapsed time (in milliseconds)
* that the thread associated with this <tt>ThreadInfo</tt>
* has waited for notification
* since thread contention monitoring is enabled.
* I.e. the total accumulated time the thread has been in the
* {@link java.lang.Thread.State#WAITING WAITING}
* or {@link java.lang.Thread.State#TIMED_WAITING TIMED_WAITING} state
* since thread contention monitoring is enabled.
* This method returns <tt>-1</tt> if thread contention monitoring
* is disabled.
*
* <p>The Java virtual machine may measure the time with a high
* resolution timer. This statistic is reset when
* the thread contention monitoring is reenabled.
*
* @return the approximate accumulated elapsed time in milliseconds
* that a thread has been in the <tt>WAITING</tt> or
* <tt>TIMED_WAITING</tt> state;
* <tt>-1</tt> if thread contention monitoring is disabled.
*
* @throws java.lang.UnsupportedOperationException if the Java
* virtual machine does not support this operation.
*
* @see ThreadMXBean#isThreadContentionMonitoringSupported
* @see ThreadMXBean#setThreadContentionMonitoringEnabled
*/
public long getWaitedTime() {
return waitedTime;
}
/**
* Returns the total number of times that
* the thread associated with this <tt>ThreadInfo</tt>
* waited for notification.
* I.e. the number of times that a thread has been
* in the {@link java.lang.Thread.State#WAITING WAITING}
* or {@link java.lang.Thread.State#TIMED_WAITING TIMED_WAITING} state.
*
* @return the total number of times that the thread
* was in the <tt>WAITING</tt> or <tt>TIMED_WAITING</tt> state.
*/
public long getWaitedCount() {
return waitedCount;
}
/**
* Returns the <tt>LockInfo</tt> of an object for which
* the thread associated with this <tt>ThreadInfo</tt>
* is blocked waiting.
* A thread can be blocked waiting for one of the following:
* <ul>
* <li>an object monitor to be acquired for entering or reentering
* a synchronization block/method.
* <br>The thread is in the {@link java.lang.Thread.State#BLOCKED BLOCKED}
* state waiting to enter the <tt>synchronized</tt> statement
* or method.
* <p></li>
* <li>an object monitor to be notified by another thread.
* <br>The thread is in the {@link java.lang.Thread.State#WAITING WAITING}
* or {@link java.lang.Thread.State#TIMED_WAITING TIMED_WAITING} state
* due to a call to the {@link Object#wait Object.wait} method.
* <p></li>
* <li>a synchronization object responsible for the thread parking.
* <br>The thread is in the {@link java.lang.Thread.State#WAITING WAITING}
* or {@link java.lang.Thread.State#TIMED_WAITING TIMED_WAITING} state
* due to a call to the
* {@link java.util.concurrent.locks.LockSupport#park(Object)
* LockSupport.park} method. The synchronization object
* is the object returned from
* {@link java.util.concurrent.locks.LockSupport#getBlocker
* LockSupport.getBlocker} method. Typically it is an
* <a href="LockInfo.html#OwnableSynchronizer"> ownable synchronizer</a>
* or a {@link java.util.concurrent.locks.Condition Condition}.</li>
* </ul>
*
* <p>This method returns <tt>null</tt> if the thread is not in any of
* the above conditions.
*
* @return <tt>LockInfo</tt> of an object for which the thread
* is blocked waiting if any; <tt>null</tt> otherwise.
* @since 1.6
*/
public LockInfo getLockInfo() {
return lock;
}
/**
* Returns the {@link LockInfo#toString string representation}
* of an object for which the thread associated with this
* <tt>ThreadInfo</tt> is blocked waiting.
* This method is equivalent to calling:
* <blockquote>
* <pre>
* getLockInfo().toString()
* </pre></blockquote>
*
* <p>This method will return <tt>null</tt> if this thread is not blocked
* waiting for any object or if the object is not owned by any thread.
*
* @return the string representation of the object on which
* the thread is blocked if any;
* <tt>null</tt> otherwise.
*
* @see #getLockInfo
*/
public String getLockName() {
return lockName;
}
/**
* Returns the ID of the thread which owns the object
* for which the thread associated with this <tt>ThreadInfo</tt>
* is blocked waiting.
* This method will return <tt>-1</tt> if this thread is not blocked
* waiting for any object or if the object is not owned by any thread.
*
* @return the thread ID of the owner thread of the object
* this thread is blocked on;
* <tt>-1</tt> if this thread is not blocked
* or if the object is not owned by any thread.
*
* @see #getLockInfo
*/
public long getLockOwnerId() {
return lockOwnerId;
}
/**
* Returns the name of the thread which owns the object
* for which the thread associated with this <tt>ThreadInfo</tt>
* is blocked waiting.
* This method will return <tt>null</tt> if this thread is not blocked
* waiting for any object or if the object is not owned by any thread.
*
* @return the name of the thread that owns the object
* this thread is blocked on;
* <tt>null</tt> if this thread is not blocked
* or if the object is not owned by any thread.
*
* @see #getLockInfo
*/
public String getLockOwnerName() {
return lockOwnerName;
}
/**
* Returns the stack trace of the thread
* associated with this <tt>ThreadInfo</tt>.
* If no stack trace was requested for this thread info, this method
* will return a zero-length array.
* If the returned array is of non-zero length then the first element of
* the array represents the top of the stack, which is the most recent
* method invocation in the sequence. The last element of the array
* represents the bottom of the stack, which is the least recent method
* invocation in the sequence.
*
* <p>Some Java virtual machines may, under some circumstances, omit one
* or more stack frames from the stack trace. In the extreme case,
* a virtual machine that has no stack trace information concerning
* the thread associated with this <tt>ThreadInfo</tt>
* is permitted to return a zero-length array from this method.
*
* @return an array of <tt>StackTraceElement</tt> objects of the thread.
*/
public StackTraceElement[] getStackTrace() {
return stackTrace;
}
/**
* Tests if the thread associated with this <tt>ThreadInfo</tt>
* is suspended. This method returns <tt>true</tt> if
* {@link Thread#suspend} has been called.
*
* @return <tt>true</tt> if the thread is suspended;
* <tt>false</tt> otherwise.
*/
public boolean isSuspended() {
return suspended;
}
/**
* Tests if the thread associated with this <tt>ThreadInfo</tt>
* is executing native code via the Java Native Interface (JNI).
* The JNI native code does not include
* the virtual machine support code or the compiled native
* code generated by the virtual machine.
*
* @return <tt>true</tt> if the thread is executing native code;
* <tt>false</tt> otherwise.
*/
public boolean isInNative() {
return inNative;
}
/**
* Returns a string representation of this thread info.
* The format of this string depends on the implementation.
* The returned string will typically include
* the {@linkplain #getThreadName thread name},
* the {@linkplain #getThreadId thread ID},
* its {@linkplain #getThreadState state},
* and a {@linkplain #getStackTrace stack trace} if any.
*
* @return a string representation of this thread info.
*/
public String toString() {
StringBuilder sb = new StringBuilder("\"" + getThreadName() + "\"" +
" Id=" + getThreadId() + " " +
getThreadState());
if (getLockName() != null) {
sb.append(" on " + getLockName());
}
if (getLockOwnerName() != null) {
sb.append(" owned by \"" + getLockOwnerName() +
"\" Id=" + getLockOwnerId());
}
if (isSuspended()) {
sb.append(" (suspended)");
}
if (isInNative()) {
sb.append(" (in native)");
}
sb.append('\n');
int i = 0;
for (; i < stackTrace.length && i < MAX_FRAMES; i++) {
StackTraceElement ste = stackTrace[i];
sb.append("\tat " + ste.toString());
sb.append('\n');
if (i == 0 && getLockInfo() != null) {
Thread.State ts = getThreadState();
switch (ts) {
case BLOCKED:
sb.append("\t- blocked on " + getLockInfo());
sb.append('\n');
break;
case WAITING:
sb.append("\t- waiting on " + getLockInfo());
sb.append('\n');
break;
case TIMED_WAITING:
sb.append("\t- waiting on " + getLockInfo());
sb.append('\n');
break;
default:
}
}
for (MonitorInfo mi : lockedMonitors) {
if (mi.getLockedStackDepth() == i) {
sb.append("\t- locked " + mi);
sb.append('\n');
}
}
}
if (i < stackTrace.length) {
sb.append("\t...");
sb.append('\n');
}
LockInfo[] locks = getLockedSynchronizers();
if (locks.length > 0) {
sb.append("\n\tNumber of locked synchronizers = " + locks.length);
sb.append('\n');
for (LockInfo li : locks) {
sb.append("\t- " + li);
sb.append('\n');
}
}
sb.append('\n');
return sb.toString();
}
private static final int MAX_FRAMES = 8;
/**
* Returns a <tt>ThreadInfo</tt> object represented by the
* given <tt>CompositeData</tt>.
* The given <tt>CompositeData</tt> must contain the following attributes
* unless otherwise specified below:
* <blockquote>
* <table border summary="The attributes and their types the given CompositeData contains">
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
* </tr>
* <tr>
* <td>threadId</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* <tr>
* <td>threadName</td>
* <td><tt>java.lang.String</tt></td>
* </tr>
* <tr>
* <td>threadState</td>
* <td><tt>java.lang.String</tt></td>
* </tr>
* <tr>
* <td>suspended</td>
* <td><tt>java.lang.Boolean</tt></td>
* </tr>
* <tr>
* <td>inNative</td>
* <td><tt>java.lang.Boolean</tt></td>
* </tr>
* <tr>
* <td>blockedCount</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* <tr>
* <td>blockedTime</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* <tr>
* <td>waitedCount</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* <tr>
* <td>waitedTime</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* <tr>
* <td>lockInfo</td>
* <td><tt>javax.management.openmbean.CompositeData</tt>
* - the mapped type for {@link LockInfo} as specified in the
* {@link LockInfo#from} method.
* <p>
* If <tt>cd</tt> does not contain this attribute,
* the <tt>LockInfo</tt> object will be constructed from
* the value of the <tt>lockName</tt> attribute. </td>
* </tr>
* <tr>
* <td>lockName</td>
* <td><tt>java.lang.String</tt></td>
* </tr>
* <tr>
* <td>lockOwnerId</td>
* <td><tt>java.lang.Long</tt></td>
* </tr>
* <tr>
* <td>lockOwnerName</td>
* <td><tt>java.lang.String</tt></td>
* </tr>
* <tr>
* <td><a name="StackTrace">stackTrace</a></td>
* <td><tt>javax.management.openmbean.CompositeData[]</tt>
* <p>
* Each element is a <tt>CompositeData</tt> representing
* StackTraceElement containing the following attributes:
* <blockquote>
* <table cellspacing=1 cellpadding=0 summary="The attributes and their types the given CompositeData contains">
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
* </tr>
* <tr>
* <td>className</td>
* <td><tt>java.lang.String</tt></td>
* </tr>
* <tr>
* <td>methodName</td>
* <td><tt>java.lang.String</tt></td>
* </tr>
* <tr>
* <td>fileName</td>
* <td><tt>java.lang.String</tt></td>
* </tr>
* <tr>
* <td>lineNumber</td>
* <td><tt>java.lang.Integer</tt></td>
* </tr>
* <tr>
* <td>nativeMethod</td>
* <td><tt>java.lang.Boolean</tt></td>
* </tr>
* </table>
* </blockquote>
* </td>
* </tr>
* <tr>
* <td>lockedMonitors</td>
* <td><tt>javax.management.openmbean.CompositeData[]</tt>
* whose element type is the mapped type for
* {@link MonitorInfo} as specified in the
* {@link MonitorInfo#from Monitor.from} method.
* <p>
* If <tt>cd</tt> does not contain this attribute,
* this attribute will be set to an empty array. </td>
* </tr>
* <tr>
* <td>lockedSynchronizers</td>
* <td><tt>javax.management.openmbean.CompositeData[]</tt>
* whose element type is the mapped type for
* {@link LockInfo} as specified in the {@link LockInfo#from} method.
* <p>
* If <tt>cd</tt> does not contain this attribute,
* this attribute will be set to an empty array. </td>
* </tr>
* </table>
* </blockquote>
*
* @param cd <tt>CompositeData</tt> representing a <tt>ThreadInfo</tt>
*
* @throws IllegalArgumentException if <tt>cd</tt> does not
* represent a <tt>ThreadInfo</tt> with the attributes described
* above.
*
* @return a <tt>ThreadInfo</tt> object represented
* by <tt>cd</tt> if <tt>cd</tt> is not <tt>null</tt>;
* <tt>null</tt> otherwise.
*/
public static ThreadInfo from(CompositeData cd) {
if (cd == null) {
return null;
}
if (cd instanceof ThreadInfoCompositeData) {
return ((ThreadInfoCompositeData) cd).getThreadInfo();
} else {
return new ThreadInfo(cd);
}
}
/**
* Returns an array of {@link MonitorInfo} objects, each of which
* represents an object monitor currently locked by the thread
* associated with this <tt>ThreadInfo</tt>.
* If no locked monitor was requested for this thread info or
* no monitor is locked by the thread, this method
* will return a zero-length array.
*
* @return an array of <tt>MonitorInfo</tt> objects representing
* the object monitors locked by the thread.
*
* @since 1.6
*/
public MonitorInfo[] getLockedMonitors() {
return lockedMonitors;
}
/**
* Returns an array of {@link LockInfo} objects, each of which
* represents an <a href="LockInfo.html#OwnableSynchronizer">ownable
* synchronizer</a> currently locked by the thread associated with
* this <tt>ThreadInfo</tt>. If no locked synchronizer was
* requested for this thread info or no synchronizer is locked by
* the thread, this method will return a zero-length array.
*
* @return an array of <tt>LockInfo</tt> objects representing
* the ownable synchronizers locked by the thread.
*
* @since 1.6
*/
public LockInfo[] getLockedSynchronizers() {
return lockedSynchronizers;
}
private static final StackTraceElement[] NO_STACK_TRACE =
new StackTraceElement[0];
}

View File

@@ -0,0 +1,806 @@
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
import java.util.Map;
/**
* The management interface for the thread system of
* the Java virtual machine.
*
* <p> A Java virtual machine has a single instance of the implementation
* class of this interface. This instance implementing this interface is
* an <a href="ManagementFactory.html#MXBean">MXBean</a>
* that can be obtained by calling
* the {@link ManagementFactory#getThreadMXBean} method or
* from the {@link ManagementFactory#getPlatformMBeanServer
* platform <tt>MBeanServer</tt>} method.
*
* <p>The <tt>ObjectName</tt> for uniquely identifying the MXBean for
* the thread system within an MBeanServer is:
* <blockquote>
* {@link ManagementFactory#THREAD_MXBEAN_NAME
* <tt>java.lang:type=Threading</tt>}
* </blockquote>
*
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <h3>Thread ID</h3>
* Thread ID is a positive long value returned by calling the
* {@link java.lang.Thread#getId} method for a thread.
* The thread ID is unique during its lifetime. When a thread
* is terminated, this thread ID may be reused.
*
* <p> Some methods in this interface take a thread ID or an array
* of thread IDs as the input parameter and return per-thread information.
*
* <h3>Thread CPU time</h3>
* A Java virtual machine implementation may support measuring
* the CPU time for the current thread, for any thread, or for no threads.
*
* <p>
* The {@link #isThreadCpuTimeSupported} method can be used to determine
* if a Java virtual machine supports measuring of the CPU time for any
* thread. The {@link #isCurrentThreadCpuTimeSupported} method can
* be used to determine if a Java virtual machine supports measuring of
* the CPU time for the current thread.
* A Java virtual machine implementation that supports CPU time measurement
* for any thread will also support that for the current thread.
*
* <p> The CPU time provided by this interface has nanosecond precision
* but not necessarily nanosecond accuracy.
*
* <p>
* A Java virtual machine may disable CPU time measurement
* by default.
* The {@link #isThreadCpuTimeEnabled} and {@link #setThreadCpuTimeEnabled}
* methods can be used to test if CPU time measurement is enabled
* and to enable/disable this support respectively.
* Enabling thread CPU measurement could be expensive in some
* Java virtual machine implementations.
*
* <h3>Thread Contention Monitoring</h3>
* Some Java virtual machines may support thread contention monitoring.
* When thread contention monitoring is enabled, the accumulated elapsed
* time that the thread has blocked for synchronization or waited for
* notification will be collected and returned in the
* <a href="ThreadInfo.html#SyncStats"><tt>ThreadInfo</tt></a> object.
* <p>
* The {@link #isThreadContentionMonitoringSupported} method can be used to
* determine if a Java virtual machine supports thread contention monitoring.
* The thread contention monitoring is disabled by default. The
* {@link #setThreadContentionMonitoringEnabled} method can be used to enable
* thread contention monitoring.
*
* <h3>Synchronization Information and Deadlock Detection</h3>
* Some Java virtual machines may support monitoring of
* {@linkplain #isObjectMonitorUsageSupported object monitor usage} and
* {@linkplain #isSynchronizerUsageSupported ownable synchronizer usage}.
* The {@link #getThreadInfo(long[], boolean, boolean)} and
* {@link #dumpAllThreads} methods can be used to obtain the thread stack trace
* and synchronization information including which
* {@linkplain LockInfo <i>lock</i>} a thread is blocked to
* acquire or waiting on and which locks the thread currently owns.
* <p>
* The <tt>ThreadMXBean</tt> interface provides the
* {@link #findMonitorDeadlockedThreads} and
* {@link #findDeadlockedThreads} methods to find deadlocks in
* the running application.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a>
* @see <a href="package-summary.html#examples">
* Ways to Access MXBeans</a>
*
* @author Mandy Chung
* @since 1.5
*/
public interface ThreadMXBean extends PlatformManagedObject {
/**
* Returns the current number of live threads including both
* daemon and non-daemon threads.
*
* @return the current number of live threads.
*/
public int getThreadCount();
/**
* Returns the peak live thread count since the Java virtual machine
* started or peak was reset.
*
* @return the peak live thread count.
*/
public int getPeakThreadCount();
/**
* Returns the total number of threads created and also started
* since the Java virtual machine started.
*
* @return the total number of threads started.
*/
public long getTotalStartedThreadCount();
/**
* Returns the current number of live daemon threads.
*
* @return the current number of live daemon threads.
*/
public int getDaemonThreadCount();
/**
* Returns all live thread IDs.
* Some threads included in the returned array
* may have been terminated when this method returns.
*
* @return an array of <tt>long</tt>, each is a thread ID.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
*/
public long[] getAllThreadIds();
/**
* Returns the thread info for a thread of the specified
* <tt>id</tt> with no stack trace.
* This method is equivalent to calling:
* <blockquote>
* {@link #getThreadInfo(long, int) getThreadInfo(id, 0);}
* </blockquote>
*
* <p>
* This method returns a <tt>ThreadInfo</tt> object representing
* the thread information for the thread of the specified ID.
* The stack trace, locked monitors, and locked synchronizers
* in the returned <tt>ThreadInfo</tt> object will
* be empty.
*
* If a thread of the given ID is not alive or does not exist,
* this method will return <tt>null</tt>. A thread is alive if
* it has been started and has not yet died.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>ThreadInfo</tt> is
* <tt>CompositeData</tt> with attributes as specified in the
* {@link ThreadInfo#from ThreadInfo.from} method.
*
* @param id the thread ID of the thread. Must be positive.
*
* @return a {@link ThreadInfo} object for the thread of the given ID
* with no stack trace, no locked monitor and no synchronizer info;
* <tt>null</tt> if the thread of the given ID is not alive or
* it does not exist.
*
* @throws IllegalArgumentException if {@code id <= 0}.
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
*/
public ThreadInfo getThreadInfo(long id);
/**
* Returns the thread info for each thread
* whose ID is in the input array <tt>ids</tt> with no stack trace.
* This method is equivalent to calling:
* <blockquote><pre>
* {@link #getThreadInfo(long[], int) getThreadInfo}(ids, 0);
* </pre></blockquote>
*
* <p>
* This method returns an array of the <tt>ThreadInfo</tt> objects.
* The stack trace, locked monitors, and locked synchronizers
* in each <tt>ThreadInfo</tt> object will be empty.
*
* If a thread of a given ID is not alive or does not exist,
* the corresponding element in the returned array will
* contain <tt>null</tt>. A thread is alive if
* it has been started and has not yet died.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>ThreadInfo</tt> is
* <tt>CompositeData</tt> with attributes as specified in the
* {@link ThreadInfo#from ThreadInfo.from} method.
*
* @param ids an array of thread IDs.
* @return an array of the {@link ThreadInfo} objects, each containing
* information about a thread whose ID is in the corresponding
* element of the input array of IDs
* with no stack trace, no locked monitor and no synchronizer info.
*
* @throws IllegalArgumentException if any element in the input array
* <tt>ids</tt> is {@code <= 0}.
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
*/
public ThreadInfo[] getThreadInfo(long[] ids);
/**
* Returns a thread info for a thread of the specified <tt>id</tt>,
* with stack trace of a specified number of stack trace elements.
* The <tt>maxDepth</tt> parameter indicates the maximum number of
* {@link StackTraceElement} to be retrieved from the stack trace.
* If <tt>maxDepth == Integer.MAX_VALUE</tt>, the entire stack trace of
* the thread will be dumped.
* If <tt>maxDepth == 0</tt>, no stack trace of the thread
* will be dumped.
* This method does not obtain the locked monitors and locked
* synchronizers of the thread.
* <p>
* When the Java virtual machine has no stack trace information
* about a thread or <tt>maxDepth == 0</tt>,
* the stack trace in the
* <tt>ThreadInfo</tt> object will be an empty array of
* <tt>StackTraceElement</tt>.
*
* <p>
* If a thread of the given ID is not alive or does not exist,
* this method will return <tt>null</tt>. A thread is alive if
* it has been started and has not yet died.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>ThreadInfo</tt> is
* <tt>CompositeData</tt> with attributes as specified in the
* {@link ThreadInfo#from ThreadInfo.from} method.
*
* @param id the thread ID of the thread. Must be positive.
* @param maxDepth the maximum number of entries in the stack trace
* to be dumped. <tt>Integer.MAX_VALUE</tt> could be used to request
* the entire stack to be dumped.
*
* @return a {@link ThreadInfo} of the thread of the given ID
* with no locked monitor and synchronizer info.
* <tt>null</tt> if the thread of the given ID is not alive or
* it does not exist.
*
* @throws IllegalArgumentException if {@code id <= 0}.
* @throws IllegalArgumentException if <tt>maxDepth is negative</tt>.
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
*
*/
public ThreadInfo getThreadInfo(long id, int maxDepth);
/**
* Returns the thread info for each thread
* whose ID is in the input array <tt>ids</tt>,
* with stack trace of a specified number of stack trace elements.
* The <tt>maxDepth</tt> parameter indicates the maximum number of
* {@link StackTraceElement} to be retrieved from the stack trace.
* If <tt>maxDepth == Integer.MAX_VALUE</tt>, the entire stack trace of
* the thread will be dumped.
* If <tt>maxDepth == 0</tt>, no stack trace of the thread
* will be dumped.
* This method does not obtain the locked monitors and locked
* synchronizers of the threads.
* <p>
* When the Java virtual machine has no stack trace information
* about a thread or <tt>maxDepth == 0</tt>,
* the stack trace in the
* <tt>ThreadInfo</tt> object will be an empty array of
* <tt>StackTraceElement</tt>.
* <p>
* This method returns an array of the <tt>ThreadInfo</tt> objects,
* each is the thread information about the thread with the same index
* as in the <tt>ids</tt> array.
* If a thread of the given ID is not alive or does not exist,
* <tt>null</tt> will be set in the corresponding element
* in the returned array. A thread is alive if
* it has been started and has not yet died.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>ThreadInfo</tt> is
* <tt>CompositeData</tt> with attributes as specified in the
* {@link ThreadInfo#from ThreadInfo.from} method.
*
* @param ids an array of thread IDs
* @param maxDepth the maximum number of entries in the stack trace
* to be dumped. <tt>Integer.MAX_VALUE</tt> could be used to request
* the entire stack to be dumped.
*
* @return an array of the {@link ThreadInfo} objects, each containing
* information about a thread whose ID is in the corresponding
* element of the input array of IDs with no locked monitor and
* synchronizer info.
*
* @throws IllegalArgumentException if <tt>maxDepth is negative</tt>.
* @throws IllegalArgumentException if any element in the input array
* <tt>ids</tt> is {@code <= 0}.
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
*
*/
public ThreadInfo[] getThreadInfo(long[] ids, int maxDepth);
/**
* Tests if the Java virtual machine supports thread contention monitoring.
*
* @return
* <tt>true</tt>
* if the Java virtual machine supports thread contention monitoring;
* <tt>false</tt> otherwise.
*/
public boolean isThreadContentionMonitoringSupported();
/**
* Tests if thread contention monitoring is enabled.
*
* @return <tt>true</tt> if thread contention monitoring is enabled;
* <tt>false</tt> otherwise.
*
* @throws UnsupportedOperationException if the Java virtual
* machine does not support thread contention monitoring.
*
* @see #isThreadContentionMonitoringSupported
*/
public boolean isThreadContentionMonitoringEnabled();
/**
* Enables or disables thread contention monitoring.
* Thread contention monitoring is disabled by default.
*
* @param enable <tt>true</tt> to enable;
* <tt>false</tt> to disable.
*
* @throws UnsupportedOperationException if the Java
* virtual machine does not support thread contention monitoring.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("control").
*
* @see #isThreadContentionMonitoringSupported
*/
public void setThreadContentionMonitoringEnabled(boolean enable);
/**
* Returns the total CPU time for the current thread in nanoseconds.
* The returned value is of nanoseconds precision but
* not necessarily nanoseconds accuracy.
* If the implementation distinguishes between user mode time and system
* mode time, the returned CPU time is the amount of time that
* the current thread has executed in user mode or system mode.
*
* <p>
* This is a convenience method for local management use and is
* equivalent to calling:
* <blockquote><pre>
* {@link #getThreadCpuTime getThreadCpuTime}(Thread.currentThread().getId());
* </pre></blockquote>
*
* @return the total CPU time for the current thread if CPU time
* measurement is enabled; <tt>-1</tt> otherwise.
*
* @throws UnsupportedOperationException if the Java
* virtual machine does not support CPU time measurement for
* the current thread.
*
* @see #getCurrentThreadUserTime
* @see #isCurrentThreadCpuTimeSupported
* @see #isThreadCpuTimeEnabled
* @see #setThreadCpuTimeEnabled
*/
public long getCurrentThreadCpuTime();
/**
* Returns the CPU time that the current thread has executed
* in user mode in nanoseconds.
* The returned value is of nanoseconds precision but
* not necessarily nanoseconds accuracy.
*
* <p>
* This is a convenience method for local management use and is
* equivalent to calling:
* <blockquote><pre>
* {@link #getThreadUserTime getThreadUserTime}(Thread.currentThread().getId());
* </pre></blockquote>
*
* @return the user-level CPU time for the current thread if CPU time
* measurement is enabled; <tt>-1</tt> otherwise.
*
* @throws UnsupportedOperationException if the Java
* virtual machine does not support CPU time measurement for
* the current thread.
*
* @see #getCurrentThreadCpuTime
* @see #isCurrentThreadCpuTimeSupported
* @see #isThreadCpuTimeEnabled
* @see #setThreadCpuTimeEnabled
*/
public long getCurrentThreadUserTime();
/**
* Returns the total CPU time for a thread of the specified ID in nanoseconds.
* The returned value is of nanoseconds precision but
* not necessarily nanoseconds accuracy.
* If the implementation distinguishes between user mode time and system
* mode time, the returned CPU time is the amount of time that
* the thread has executed in user mode or system mode.
*
* <p>
* If the thread of the specified ID is not alive or does not exist,
* this method returns <tt>-1</tt>. If CPU time measurement
* is disabled, this method returns <tt>-1</tt>.
* A thread is alive if it has been started and has not yet died.
* <p>
* If CPU time measurement is enabled after the thread has started,
* the Java virtual machine implementation may choose any time up to
* and including the time that the capability is enabled as the point
* where CPU time measurement starts.
*
* @param id the thread ID of a thread
* @return the total CPU time for a thread of the specified ID
* if the thread of the specified ID exists, the thread is alive,
* and CPU time measurement is enabled;
* <tt>-1</tt> otherwise.
*
* @throws IllegalArgumentException if {@code id <= 0}.
* @throws UnsupportedOperationException if the Java
* virtual machine does not support CPU time measurement for
* other threads.
*
* @see #getThreadUserTime
* @see #isThreadCpuTimeSupported
* @see #isThreadCpuTimeEnabled
* @see #setThreadCpuTimeEnabled
*/
public long getThreadCpuTime(long id);
/**
* Returns the CPU time that a thread of the specified ID
* has executed in user mode in nanoseconds.
* The returned value is of nanoseconds precision but
* not necessarily nanoseconds accuracy.
*
* <p>
* If the thread of the specified ID is not alive or does not exist,
* this method returns <tt>-1</tt>. If CPU time measurement
* is disabled, this method returns <tt>-1</tt>.
* A thread is alive if it has been started and has not yet died.
* <p>
* If CPU time measurement is enabled after the thread has started,
* the Java virtual machine implementation may choose any time up to
* and including the time that the capability is enabled as the point
* where CPU time measurement starts.
*
* @param id the thread ID of a thread
* @return the user-level CPU time for a thread of the specified ID
* if the thread of the specified ID exists, the thread is alive,
* and CPU time measurement is enabled;
* <tt>-1</tt> otherwise.
*
* @throws IllegalArgumentException if {@code id <= 0}.
* @throws UnsupportedOperationException if the Java
* virtual machine does not support CPU time measurement for
* other threads.
*
* @see #getThreadCpuTime
* @see #isThreadCpuTimeSupported
* @see #isThreadCpuTimeEnabled
* @see #setThreadCpuTimeEnabled
*/
public long getThreadUserTime(long id);
/**
* Tests if the Java virtual machine implementation supports CPU time
* measurement for any thread.
* A Java virtual machine implementation that supports CPU time
* measurement for any thread will also support CPU time
* measurement for the current thread.
*
* @return
* <tt>true</tt>
* if the Java virtual machine supports CPU time
* measurement for any thread;
* <tt>false</tt> otherwise.
*/
public boolean isThreadCpuTimeSupported();
/**
* Tests if the Java virtual machine supports CPU time
* measurement for the current thread.
* This method returns <tt>true</tt> if {@link #isThreadCpuTimeSupported}
* returns <tt>true</tt>.
*
* @return
* <tt>true</tt>
* if the Java virtual machine supports CPU time
* measurement for current thread;
* <tt>false</tt> otherwise.
*/
public boolean isCurrentThreadCpuTimeSupported();
/**
* Tests if thread CPU time measurement is enabled.
*
* @return <tt>true</tt> if thread CPU time measurement is enabled;
* <tt>false</tt> otherwise.
*
* @throws UnsupportedOperationException if the Java virtual
* machine does not support CPU time measurement for other threads
* nor for the current thread.
*
* @see #isThreadCpuTimeSupported
* @see #isCurrentThreadCpuTimeSupported
*/
public boolean isThreadCpuTimeEnabled();
/**
* Enables or disables thread CPU time measurement. The default
* is platform dependent.
*
* @param enable <tt>true</tt> to enable;
* <tt>false</tt> to disable.
*
* @throws UnsupportedOperationException if the Java
* virtual machine does not support CPU time measurement for
* any threads nor for the current thread.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("control").
*
* @see #isThreadCpuTimeSupported
* @see #isCurrentThreadCpuTimeSupported
*/
public void setThreadCpuTimeEnabled(boolean enable);
/**
* Finds cycles of threads that are in deadlock waiting to acquire
* object monitors. That is, threads that are blocked waiting to enter a
* synchronization block or waiting to reenter a synchronization block
* after an {@link Object#wait Object.wait} call,
* where each thread owns one monitor while
* trying to obtain another monitor already held by another thread
* in a cycle.
* <p>
* More formally, a thread is <em>monitor deadlocked</em> if it is
* part of a cycle in the relation "is waiting for an object monitor
* owned by". In the simplest case, thread A is blocked waiting
* for a monitor owned by thread B, and thread B is blocked waiting
* for a monitor owned by thread A.
* <p>
* This method is designed for troubleshooting use, but not for
* synchronization control. It might be an expensive operation.
* <p>
* This method finds deadlocks involving only object monitors.
* To find deadlocks involving both object monitors and
* <a href="LockInfo.html#OwnableSynchronizer">ownable synchronizers</a>,
* the {@link #findDeadlockedThreads findDeadlockedThreads} method
* should be used.
*
* @return an array of IDs of the threads that are monitor
* deadlocked, if any; <tt>null</tt> otherwise.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
*
* @see #findDeadlockedThreads
*/
public long[] findMonitorDeadlockedThreads();
/**
* Resets the peak thread count to the current number of
* live threads.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("control").
*
* @see #getPeakThreadCount
* @see #getThreadCount
*/
public void resetPeakThreadCount();
/**
* Finds cycles of threads that are in deadlock waiting to acquire
* object monitors or
* <a href="LockInfo.html#OwnableSynchronizer">ownable synchronizers</a>.
*
* Threads are <em>deadlocked</em> in a cycle waiting for a lock of
* these two types if each thread owns one lock while
* trying to acquire another lock already held
* by another thread in the cycle.
* <p>
* This method is designed for troubleshooting use, but not for
* synchronization control. It might be an expensive operation.
*
* @return an array of IDs of the threads that are
* deadlocked waiting for object monitors or ownable synchronizers, if any;
* <tt>null</tt> otherwise.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
* @throws UnsupportedOperationException if the Java virtual
* machine does not support monitoring of ownable synchronizer usage.
*
* @see #isSynchronizerUsageSupported
* @see #findMonitorDeadlockedThreads
* @since 1.6
*/
public long[] findDeadlockedThreads();
/**
* Tests if the Java virtual machine supports monitoring of
* object monitor usage.
*
* @return
* <tt>true</tt>
* if the Java virtual machine supports monitoring of
* object monitor usage;
* <tt>false</tt> otherwise.
*
* @see #dumpAllThreads
* @since 1.6
*/
public boolean isObjectMonitorUsageSupported();
/**
* Tests if the Java virtual machine supports monitoring of
* <a href="LockInfo.html#OwnableSynchronizer">
* ownable synchronizer</a> usage.
*
* @return
* <tt>true</tt>
* if the Java virtual machine supports monitoring of ownable
* synchronizer usage;
* <tt>false</tt> otherwise.
*
* @see #dumpAllThreads
* @since 1.6
*/
public boolean isSynchronizerUsageSupported();
/**
* Returns the thread info for each thread
* whose ID is in the input array <tt>ids</tt>, with stack trace
* and synchronization information.
*
* <p>
* This method obtains a snapshot of the thread information
* for each thread including:
* <ul>
* <li>the entire stack trace,</li>
* <li>the object monitors currently locked by the thread
* if <tt>lockedMonitors</tt> is <tt>true</tt>, and</li>
* <li>the <a href="LockInfo.html#OwnableSynchronizer">
* ownable synchronizers</a> currently locked by the thread
* if <tt>lockedSynchronizers</tt> is <tt>true</tt>.</li>
* </ul>
* <p>
* This method returns an array of the <tt>ThreadInfo</tt> objects,
* each is the thread information about the thread with the same index
* as in the <tt>ids</tt> array.
* If a thread of the given ID is not alive or does not exist,
* <tt>null</tt> will be set in the corresponding element
* in the returned array. A thread is alive if
* it has been started and has not yet died.
* <p>
* If a thread does not lock any object monitor or <tt>lockedMonitors</tt>
* is <tt>false</tt>, the returned <tt>ThreadInfo</tt> object will have an
* empty <tt>MonitorInfo</tt> array. Similarly, if a thread does not
* lock any synchronizer or <tt>lockedSynchronizers</tt> is <tt>false</tt>,
* the returned <tt>ThreadInfo</tt> object
* will have an empty <tt>LockInfo</tt> array.
*
* <p>
* When both <tt>lockedMonitors</tt> and <tt>lockedSynchronizers</tt>
* parameters are <tt>false</tt>, it is equivalent to calling:
* <blockquote><pre>
* {@link #getThreadInfo(long[], int) getThreadInfo(ids, Integer.MAX_VALUE)}
* </pre></blockquote>
*
* <p>
* This method is designed for troubleshooting use, but not for
* synchronization control. It might be an expensive operation.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>ThreadInfo</tt> is
* <tt>CompositeData</tt> with attributes as specified in the
* {@link ThreadInfo#from ThreadInfo.from} method.
*
* @param ids an array of thread IDs.
* @param lockedMonitors if <tt>true</tt>, retrieves all locked monitors.
* @param lockedSynchronizers if <tt>true</tt>, retrieves all locked
* ownable synchronizers.
*
* @return an array of the {@link ThreadInfo} objects, each containing
* information about a thread whose ID is in the corresponding
* element of the input array of IDs.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
* @throws UnsupportedOperationException
* <ul>
* <li>if <tt>lockedMonitors</tt> is <tt>true</tt> but
* the Java virtual machine does not support monitoring
* of {@linkplain #isObjectMonitorUsageSupported
* object monitor usage}; or</li>
* <li>if <tt>lockedSynchronizers</tt> is <tt>true</tt> but
* the Java virtual machine does not support monitoring
* of {@linkplain #isSynchronizerUsageSupported
* ownable synchronizer usage}.</li>
* </ul>
*
* @see #isObjectMonitorUsageSupported
* @see #isSynchronizerUsageSupported
*
* @since 1.6
*/
public ThreadInfo[] getThreadInfo(long[] ids, boolean lockedMonitors, boolean lockedSynchronizers);
/**
* Returns the thread info for all live threads with stack trace
* and synchronization information.
* Some threads included in the returned array
* may have been terminated when this method returns.
*
* <p>
* This method returns an array of {@link ThreadInfo} objects
* as specified in the {@link #getThreadInfo(long[], boolean, boolean)}
* method.
*
* @param lockedMonitors if <tt>true</tt>, dump all locked monitors.
* @param lockedSynchronizers if <tt>true</tt>, dump all locked
* ownable synchronizers.
*
* @return an array of {@link ThreadInfo} for all live threads.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
* @throws UnsupportedOperationException
* <ul>
* <li>if <tt>lockedMonitors</tt> is <tt>true</tt> but
* the Java virtual machine does not support monitoring
* of {@linkplain #isObjectMonitorUsageSupported
* object monitor usage}; or</li>
* <li>if <tt>lockedSynchronizers</tt> is <tt>true</tt> but
* the Java virtual machine does not support monitoring
* of {@linkplain #isSynchronizerUsageSupported
* ownable synchronizer usage}.</li>
* </ul>
*
* @see #isObjectMonitorUsageSupported
* @see #isSynchronizerUsageSupported
*
* @since 1.6
*/
public ThreadInfo[] dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers);
}