Path: blob/master/src/java.management/share/classes/java/lang/management/MemoryPoolMXBean.java
41159 views
/*1* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.lang.management;2627/**28* The management interface for a memory pool. A memory pool29* represents the memory resource managed by the Java virtual machine30* and is managed by one or more {@link MemoryManagerMXBean memory managers}.31*32* <p> A Java virtual machine has one or more instances of the33* implementation class of this interface. An instance34* implementing this interface is35* an <a href="ManagementFactory.html#MXBean">MXBean</a>36* that can be obtained by calling37* the {@link ManagementFactory#getMemoryPoolMXBeans} method or38* from the {@link ManagementFactory#getPlatformMBeanServer39* platform MBeanServer} method.40*41* <p>The {@code ObjectName} for uniquely identifying the MXBean for42* a memory pool within an {@code MBeanServer} is:43* <blockquote>44* {@link ManagementFactory#MEMORY_POOL_MXBEAN_DOMAIN_TYPE45* java.lang:type=MemoryPool}{@code ,name=}<i>pool's name</i>46* </blockquote>47*48* It can be obtained by calling the49* {@link PlatformManagedObject#getObjectName} method.50*51* <h2>Memory Type</h2>52* <p>The Java virtual machine has a heap for object allocation and also53* maintains non-heap memory for the method area and the Java virtual54* machine execution. The Java virtual machine can have one or more55* memory pools. Each memory pool represents a memory area56* of one of the following types:57* <ul>58* <li>{@link MemoryType#HEAP heap}</li>59* <li>{@link MemoryType#NON_HEAP non-heap}</li>60* </ul>61*62* <h2>Memory Usage Monitoring</h2>63*64* A memory pool has the following attributes:65* <ul>66* <li><a href="#Usage">Memory usage</a></li>67* <li><a href="#PeakUsage">Peak memory usage</a></li>68* <li><a href="#UsageThreshold">Usage Threshold</a></li>69* <li><a href="#CollectionThreshold">Collection Usage Threshold</a>70* (only supported by some <em>garbage-collected</em> memory pools)</li>71* </ul>72*73* <h3><a id="Usage">1. Memory Usage</a></h3>74*75* The {@link #getUsage} method provides an estimate76* of the current usage of a memory pool.77* For a garbage-collected memory pool, the amount of used memory78* includes the memory occupied by all objects in the pool79* including both <em>reachable</em> and <em>unreachable</em> objects.80*81* <p>In general, this method is a lightweight operation for getting82* an approximate memory usage. For some memory pools, for example,83* when objects are not packed contiguously, this method may be84* an expensive operation that requires some computation to determine85* the current memory usage. An implementation should document when86* this is the case.87*88* <h3><a id="PeakUsage">2. Peak Memory Usage</a></h3>89*90* The Java virtual machine maintains the peak memory usage of a memory91* pool since the virtual machine was started or the peak was reset.92* The peak memory usage is returned by the {@link #getPeakUsage} method93* and reset by calling the {@link #resetPeakUsage} method.94*95* <h3><a id="UsageThreshold">3. Usage Threshold</a></h3>96*97* Each memory pool has a manageable attribute98* called the <i>usage threshold</i> which has a default value supplied99* by the Java virtual machine. The default value is platform-dependent.100* The usage threshold can be set via the101* {@link #setUsageThreshold setUsageThreshold} method.102* If the threshold is set to a positive value, the usage threshold crossing103* checking is enabled in this memory pool.104* If the usage threshold is set to zero, usage105* threshold crossing checking on this memory pool is disabled.106* The {@link MemoryPoolMXBean#isUsageThresholdSupported} method can107* be used to determine if this functionality is supported.108* <p>109* A Java virtual machine performs usage threshold crossing checking on a110* memory pool basis at its best appropriate time, typically,111* at garbage collection time.112* Each memory pool maintains a {@link #getUsageThresholdCount113* usage threshold count} that will get incremented114* every time when the Java virtual machine115* detects that the memory pool usage is crossing the threshold.116* <p>117* This manageable usage threshold attribute is designed for monitoring the118* increasing trend of memory usage with low overhead.119* Usage threshold may not be appropriate for some memory pools.120* For example, a generational garbage collector, a common garbage collection121* algorithm used in many Java virtual machine implementations,122* manages two or more generations segregating objects by age.123* Most of the objects are allocated in124* the <em>youngest generation</em> (say a nursery memory pool).125* The nursery memory pool is designed to be filled up and126* collecting the nursery memory pool will free most of its memory space127* since it is expected to contain mostly short-lived objects128* and mostly are unreachable at garbage collection time.129* In this case, it is more appropriate for the nursery memory pool130* not to support a usage threshold. In addition,131* if the cost of an object allocation132* in one memory pool is very low (for example, just atomic pointer exchange),133* the Java virtual machine would probably not support the usage threshold134* for that memory pool since the overhead in comparing the usage with135* the threshold is higher than the cost of object allocation.136*137* <p>138* The memory usage of the system can be monitored using139* <a href="#Polling">polling</a> or140* <a href="#ThresholdNotification">threshold notification</a> mechanisms.141*142* <ol type="a">143* <li><a id="Polling"><b>Polling</b></a>144* <p>145* An application can continuously monitor its memory usage146* by calling either the {@link #getUsage} method for all147* memory pools or the {@link #isUsageThresholdExceeded} method148* for those memory pools that support a usage threshold.149* Below is example code that has a thread dedicated for150* task distribution and processing. At every interval,151* it will determine if it should receive and process new tasks based152* on its memory usage. If the memory usage exceeds its usage threshold,153* it will redistribute all outstanding tasks to other VMs and154* stop receiving new tasks until the memory usage returns155* below its usage threshold.156*157* <pre>158* // Assume the usage threshold is supported for this pool.159* // Set the threshold to myThreshold above which no new tasks160* // should be taken.161* pool.setUsageThreshold(myThreshold);162* ....163*164* boolean lowMemory = false;165* while (true) {166* if (pool.isUsageThresholdExceeded()) {167* // potential low memory, so redistribute tasks to other VMs168* lowMemory = true;169* redistributeTasks();170* // stop receiving new tasks171* stopReceivingTasks();172* } else {173* if (lowMemory) {174* // resume receiving tasks175* lowMemory = false;176* resumeReceivingTasks();177* }178* // processing outstanding task179* ...180* }181* // sleep for sometime182* try {183* Thread.sleep(sometime);184* } catch (InterruptedException e) {185* ...186* }187* }188* </pre>189*190* <hr>191* The above example does not differentiate the case where192* the memory usage has temporarily dropped below the usage threshold193* from the case where the memory usage remains above the threshold194* between two iterations. The usage threshold count returned by195* the {@link #getUsageThresholdCount} method196* can be used to determine197* if the memory usage has returned below the threshold198* between two polls.199* <p>200* Below shows another example that takes some action if a201* memory pool is under low memory and ignores the memory usage202* changes during the action processing time.203*204* <pre>205* // Assume the usage threshold is supported for this pool.206* // Set the threshold to myThreshold which determines if207* // the application will take some action under low memory condition.208* pool.setUsageThreshold(myThreshold);209*210* int prevCrossingCount = 0;211* while (true) {212* // A busy loop to detect when the memory usage213* // has exceeded the threshold.214* while (!pool.isUsageThresholdExceeded() ||215* pool.getUsageThresholdCount() == prevCrossingCount) {216* try {217* Thread.sleep(sometime)218* } catch (InterruptException e) {219* ....220* }221* }222*223* // Do some processing such as check for memory usage224* // and issue a warning225* ....226*227* // Gets the current threshold count. The busy loop will then228* // ignore any crossing of threshold happens during the processing.229* prevCrossingCount = pool.getUsageThresholdCount();230* }231* </pre><hr>232* </li>233* <li><a id="ThresholdNotification"><b>Usage Threshold Notifications</b></a>234* <p>235* Usage threshold notification will be emitted by {@link MemoryMXBean}.236* When the Java virtual machine detects that the memory usage of237* a memory pool has reached or exceeded the usage threshold238* the virtual machine will trigger the {@code MemoryMXBean} to emit an239* {@link MemoryNotificationInfo#MEMORY_THRESHOLD_EXCEEDED240* usage threshold exceeded notification}.241* Another usage threshold exceeded notification will not be242* generated until the usage has fallen below the threshold and243* then exceeded it again.244* <p>245* Below is an example code implementing the same logic as the246* first example above but using the usage threshold notification247* mechanism to detect low memory conditions instead of polling.248* In this example code, upon receiving notification, the notification249* listener notifies another thread to perform the actual action250* such as to redistribute outstanding tasks, stop receiving tasks,251* or resume receiving tasks.252* The {@code handleNotification} method should be designed to253* do a very minimal amount of work and return without delay to avoid254* causing delay in delivering subsequent notifications. Time-consuming255* actions should be performed by a separate thread.256* The notification listener may be invoked by multiple threads257* concurrently; so the tasks performed by the listener258* should be properly synchronized.259*260* <pre>261* class MyListener implements javax.management.NotificationListener {262* public void handleNotification(Notification notification, Object handback) {263* String notifType = notification.getType();264* if (notifType.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {265* // potential low memory, notify another thread266* // to redistribute outstanding tasks to other VMs267* // and stop receiving new tasks.268* lowMemory = true;269* notifyAnotherThread(lowMemory);270* }271* }272* }273*274* // Register MyListener with MemoryMXBean275* MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();276* NotificationEmitter emitter = (NotificationEmitter) mbean;277* MyListener listener = new MyListener();278* emitter.addNotificationListener(listener, null, null);279*280* // Assume this pool supports a usage threshold.281* // Set the threshold to myThreshold above which no new tasks282* // should be taken.283* pool.setUsageThreshold(myThreshold);284*285* // Usage threshold detection is enabled and notification will be286* // handled by MyListener. Continue for other processing.287* ....288*289* </pre>290* <hr>291* <p>292* There is no guarantee about when the {@code MemoryMXBean} will emit293* a threshold notification and when the notification will be delivered.294* When a notification listener is invoked, the memory usage of295* the memory pool may have crossed the usage threshold more296* than once.297* The {@link MemoryNotificationInfo#getCount} method returns the number298* of times that the memory usage has crossed the usage threshold299* at the point in time when the notification was constructed.300* It can be compared with the current usage threshold count returned301* by the {@link #getUsageThresholdCount} method to determine if302* such situation has occurred.303* </li>304* </ol>305*306* <h3><a id="CollectionThreshold">4. Collection Usage Threshold</a></h3>307*308* Collection usage threshold is a manageable attribute only applicable309* to some garbage-collected memory pools.310* After a Java virtual machine has expended effort in reclaiming memory311* space by recycling unused objects in a memory pool at garbage collection312* time, some number of bytes in the memory pools that are garbaged313* collected will still be in use. The collection usage threshold314* allows a value to be set for this number of bytes such315* that if the threshold is exceeded,316* a {@link MemoryNotificationInfo#MEMORY_THRESHOLD_EXCEEDED317* collection usage threshold exceeded notification}318* will be emitted by the {@link MemoryMXBean}.319* In addition, the {@link #getCollectionUsageThresholdCount320* collection usage threshold count} will then be incremented.321*322* <p>323* The {@link MemoryPoolMXBean#isCollectionUsageThresholdSupported} method can324* be used to determine if this functionality is supported.325*326* <p>327* A Java virtual machine performs collection usage threshold checking328* on a memory pool basis. This checking is enabled if the collection329* usage threshold is set to a positive value.330* If the collection usage threshold is set to zero, this checking331* is disabled on this memory pool. Default value is zero.332* The Java virtual machine performs the collection usage threshold333* checking at garbage collection time.334*335* <p>336* Some garbage-collected memory pools may337* choose not to support the collection usage threshold. For example,338* a memory pool is only managed by a continuous concurrent garbage339* collector. Objects can be allocated in this memory pool by some thread340* while the unused objects are reclaimed by the concurrent garbage341* collector simultaneously. Unless there is a well-defined342* garbage collection time which is the best appropriate time343* to check the memory usage, the collection usage threshold should not344* be supported.345*346* <p>347* The collection usage threshold is designed for monitoring the memory usage348* after the Java virtual machine has expended effort in reclaiming349* memory space. The collection usage could also be monitored350* by the polling and threshold notification mechanism351* described above for the <a href="#UsageThreshold">usage threshold</a>352* in a similar fashion.353*354* @see ManagementFactory#getPlatformMXBeans(Class)355* @see <a href="../../../javax/management/package-summary.html">356* JMX Specification.</a>357* @see <a href="package-summary.html#examples">358* Ways to Access MXBeans</a>359*360* @author Mandy Chung361* @since 1.5362*/363public interface MemoryPoolMXBean extends PlatformManagedObject {364/**365* Returns the name representing this memory pool.366*367* @return the name of this memory pool.368*/369public String getName();370371/**372* Returns the type of this memory pool.373*374* <p>375* <b>MBeanServer access</b>:<br>376* The mapped type of {@code MemoryType} is {@code String}377* and the value is the name of the {@code MemoryType}.378*379* @return the type of this memory pool.380*/381public MemoryType getType();382383/**384* Returns an estimate of the memory usage of this memory pool.385* This method returns {@code null}386* if this memory pool is not valid (i.e. no longer exists).387*388* <p>389* This method requests the Java virtual machine to make390* a best-effort estimate of the current memory usage of this391* memory pool. For some memory pools, this method may be an392* expensive operation that requires some computation to determine393* the estimate. An implementation should document when394* this is the case.395*396* <p>This method is designed for use in monitoring system397* memory usage and detecting low memory condition.398*399* <p>400* <b>MBeanServer access</b>:<br>401* The mapped type of {@code MemoryUsage} is402* {@code CompositeData} with attributes as specified in403* {@link MemoryUsage#from MemoryUsage}.404*405* @return a {@link MemoryUsage} object; or {@code null} if406* this pool not valid.407*/408public MemoryUsage getUsage();409410/**411* Returns the peak memory usage of this memory pool since the412* Java virtual machine was started or since the peak was reset.413* This method returns {@code null}414* if this memory pool is not valid (i.e. no longer exists).415*416* <p>417* <b>MBeanServer access</b>:<br>418* The mapped type of {@code MemoryUsage} is419* {@code CompositeData} with attributes as specified in420* {@link MemoryUsage#from MemoryUsage}.421*422* @return a {@link MemoryUsage} object representing the peak423* memory usage; or {@code null} if this pool is not valid.424*425*/426public MemoryUsage getPeakUsage();427428/**429* Resets the peak memory usage statistic of this memory pool430* to the current memory usage.431*432* @throws java.lang.SecurityException if a security manager433* exists and the caller does not have434* ManagementPermission("control").435*/436public void resetPeakUsage();437438/**439* Tests if this memory pool is valid in the Java virtual440* machine. A memory pool becomes invalid once the Java virtual441* machine removes it from the memory system.442*443* @return {@code true} if the memory pool is valid in the running444* Java virtual machine;445* {@code false} otherwise.446*/447public boolean isValid();448449/**450* Returns the name of memory managers that manages this memory pool.451* Each memory pool will be managed by at least one memory manager.452*453* @return an array of {@code String} objects, each is the name of454* a memory manager managing this memory pool.455*/456public String[] getMemoryManagerNames();457458/**459* Returns the usage threshold value of this memory pool in bytes.460* Each memory pool has a platform-dependent default threshold value.461* The current usage threshold can be changed via the462* {@link #setUsageThreshold setUsageThreshold} method.463*464* @return the usage threshold value of this memory pool in bytes.465*466* @throws UnsupportedOperationException if this memory pool467* does not support a usage threshold.468*469* @see #isUsageThresholdSupported470*/471public long getUsageThreshold();472473/**474* Sets the threshold of this memory pool to the given {@code threshold}475* value if this memory pool supports the usage threshold.476* The usage threshold crossing checking is enabled in this memory pool477* if the threshold is set to a positive value.478* The usage threshold crossing checking is disabled479* if it is set to zero.480*481* @param threshold the new threshold value in bytes. Must be non-negative.482*483* @throws IllegalArgumentException if {@code threshold} is negative484* or greater than the maximum amount of memory for485* this memory pool if defined.486*487* @throws UnsupportedOperationException if this memory pool488* does not support a usage threshold.489*490* @throws java.lang.SecurityException if a security manager491* exists and the caller does not have492* ManagementPermission("control").493*494* @see #isUsageThresholdSupported495* @see <a href="#UsageThreshold">Usage threshold</a>496*/497public void setUsageThreshold(long threshold);498499/**500* Tests if the memory usage of this memory pool501* reaches or exceeds its usage threshold value.502*503* @return {@code true} if the memory usage of504* this memory pool reaches or exceeds the threshold value;505* {@code false} otherwise.506*507* @throws UnsupportedOperationException if this memory pool508* does not support a usage threshold.509*/510public boolean isUsageThresholdExceeded();511512/**513* Returns the number of times that the memory usage has crossed514* the usage threshold.515*516* @return the number of times that the memory usage517* has crossed its usage threshold value.518*519* @throws UnsupportedOperationException if this memory pool520* does not support a usage threshold.521*/522public long getUsageThresholdCount();523524/**525* Tests if this memory pool supports usage threshold.526*527* @return {@code true} if this memory pool supports usage threshold;528* {@code false} otherwise.529*/530public boolean isUsageThresholdSupported();531532/**533* Returns the collection usage threshold value of this memory pool534* in bytes. The default value is zero. The collection usage535* threshold can be changed via the536* {@link #setCollectionUsageThreshold setCollectionUsageThreshold} method.537*538* @return the collection usage threshold of this memory pool in bytes.539*540* @throws UnsupportedOperationException if this memory pool541* does not support a collection usage threshold.542*543* @see #isCollectionUsageThresholdSupported544*/545public long getCollectionUsageThreshold();546547/**548* Sets the collection usage threshold of this memory pool to549* the given {@code threshold} value.550* When this threshold is set to positive, the Java virtual machine551* will check the memory usage at its best appropriate time after it has552* expended effort in recycling unused objects in this memory pool.553* <p>554* The collection usage threshold crossing checking is enabled555* in this memory pool if the threshold is set to a positive value.556* The collection usage threshold crossing checking is disabled557* if it is set to zero.558*559* @param threshold the new collection usage threshold value in bytes.560* Must be non-negative.561*562* @throws IllegalArgumentException if {@code threshold} is negative563* or greater than the maximum amount of memory for564* this memory pool if defined.565*566* @throws UnsupportedOperationException if this memory pool567* does not support a collection usage threshold.568*569* @throws java.lang.SecurityException if a security manager570* exists and the caller does not have571* ManagementPermission("control").572*573* @see #isCollectionUsageThresholdSupported574* @see <a href="#CollectionThreshold">Collection usage threshold</a>575*/576public void setCollectionUsageThreshold(long threshold);577578/**579* Tests if the memory usage of this memory pool after580* the most recent collection on which the Java virtual581* machine has expended effort has reached or582* exceeded its collection usage threshold.583* This method does not request the Java virtual584* machine to perform any garbage collection other than its normal585* automatic memory management.586*587* @return {@code true} if the memory usage of this memory pool588* reaches or exceeds the collection usage threshold value589* in the most recent collection;590* {@code false} otherwise.591*592* @throws UnsupportedOperationException if this memory pool593* does not support a usage threshold.594*/595public boolean isCollectionUsageThresholdExceeded();596597/**598* Returns the number of times that the Java virtual machine599* has detected that the memory usage has reached or600* exceeded the collection usage threshold.601*602* @return the number of times that the memory603* usage has reached or exceeded the collection usage threshold.604*605* @throws UnsupportedOperationException if this memory pool606* does not support a collection usage threshold.607*608* @see #isCollectionUsageThresholdSupported609*/610public long getCollectionUsageThresholdCount();611612/**613* Returns the memory usage after the Java virtual machine614* most recently expended effort in recycling unused objects615* in this memory pool.616* This method does not request the Java virtual617* machine to perform any garbage collection other than its normal618* automatic memory management.619* This method returns {@code null} if the Java virtual620* machine does not support this method.621*622* <p>623* <b>MBeanServer access</b>:<br>624* The mapped type of {@code MemoryUsage} is625* {@code CompositeData} with attributes as specified in626* {@link MemoryUsage#from MemoryUsage}.627*628* @return a {@link MemoryUsage} representing the memory usage of629* this memory pool after the Java virtual machine most recently630* expended effort in recycling unused objects;631* {@code null} if this method is not supported.632*/633public MemoryUsage getCollectionUsage();634635/**636* Tests if this memory pool supports a collection usage threshold.637*638* @return {@code true} if this memory pool supports the639* collection usage threshold; {@code false} otherwise.640*/641public boolean isCollectionUsageThresholdSupported();642}643644645