下面列出了java.lang.management.MemoryUsage#getMax ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void run(SourceFunction.SourceContext<HeapMetrics> sourceContext) throws Exception {
LOG.info("starting HeapMonitorSource");
int subtaskIndex = this.getRuntimeContext().getIndexOfThisSubtask();
String hostname = InetAddress.getLocalHost().getHostName();
while (running) {
Thread.sleep(sleepMillis);
for (MemoryPoolMXBean mpBean : ManagementFactory.getMemoryPoolMXBeans()) {
if (mpBean.getType() == MemoryType.HEAP) {
MemoryUsage memoryUsage = mpBean.getUsage();
long used = memoryUsage.getUsed();
long max = memoryUsage.getMax();
synchronized (sourceContext.getCheckpointLock()) {
sourceContext.collect(new HeapMetrics(mpBean.getName(), used, max, (double) used / max, subtaskIndex, hostname));
}
}
}
}
}
public void setUsageThreshold(long newThreshold) {
if (!isUsageThresholdSupported()) {
throw new UnsupportedOperationException(
"Usage threshold is not supported");
}
Util.checkControlAccess();
MemoryUsage usage = getUsage0();
if (newThreshold < 0) {
throw new IllegalArgumentException(
"Invalid threshold: " + newThreshold);
}
if (usage.getMax() != -1 && newThreshold > usage.getMax()) {
throw new IllegalArgumentException(
"Invalid threshold: " + newThreshold +
" must be <= maxSize." +
" Committed = " + usage.getCommitted() +
" Max = " + usage.getMax());
}
synchronized (this) {
if (!usageSensorRegistered) {
// pass the sensor to VM to begin monitoring
usageSensorRegistered = true;
setPoolUsageSensor(usageSensor);
}
setUsageThreshold0(usageThreshold, newThreshold);
this.usageThreshold = newThreshold;
}
}
public static MemoryInfo of(MemoryUsage usage) {
MemoryInfo info = new MemoryInfo();
info.max = (usage.getMax()) / 1000 / 1000;
info.used = usage.getUsed() / 1000 / 1000;
info.usage = BigDecimal.valueOf(((double) usage.getUsed() / usage.getMax()) * 100D).setScale(2, ROUND_HALF_UP)
.doubleValue();
return info;
}
public long getTenuredMax()
throws JMException
{
CompositeData data
= (CompositeData) _mbeanServer.getAttribute(getTenuredName(), "Usage");
MemoryUsage usage = MemoryUsage.from(data);
return usage.getMax();
}
public long getSurvivorFree()
throws JMException
{
CompositeData data
= (CompositeData) _mbeanServer.getAttribute(getSurvivorName(), "Usage");
MemoryUsage usage = MemoryUsage.from(data);
return usage.getMax() - usage.getUsed();
}
public void setUsageThreshold(long newThreshold) {
if (!isUsageThresholdSupported()) {
throw new UnsupportedOperationException(
"Usage threshold is not supported");
}
Util.checkControlAccess();
MemoryUsage usage = getUsage0();
if (newThreshold < 0) {
throw new IllegalArgumentException(
"Invalid threshold: " + newThreshold);
}
if (usage.getMax() != -1 && newThreshold > usage.getMax()) {
throw new IllegalArgumentException(
"Invalid threshold: " + newThreshold +
" must be <= maxSize." +
" Committed = " + usage.getCommitted() +
" Max = " + usage.getMax());
}
synchronized (this) {
if (!usageSensorRegistered) {
// pass the sensor to VM to begin monitoring
usageSensorRegistered = true;
setPoolUsageSensor(usageSensor);
}
setUsageThreshold0(usageThreshold, newThreshold);
this.usageThreshold = newThreshold;
}
}
@Override
public void handleNotification(Notification notification, Object handback) {
try {
if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
GarbageCollectionNotificationInfo info =
GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());
String gc_cause = info.getGcCause();
if (gc_cause.equals(TestExcessGCLockerCollectionsStringConstants.GCLOCKER_CAUSE)) {
Map<String, MemoryUsage> memory_before_gc = info.getGcInfo().getMemoryUsageBeforeGc();
for (String newGenPoolName : newGenPoolNames) {
MemoryUsage usage = memory_before_gc.get(newGenPoolName);
if (usage == null) continue;
double startTime = ((double) info.getGcInfo().getStartTime()) / 1000.0;
long used = usage.getUsed();
long committed = usage.getCommitted();
long max = usage.getMax();
double used_percent = (((double) used) / Math.max(committed, max)) * 100.0;
System.out.printf("%6.3f: (%s) %d/%d/%d, %8.4f%% (%s)\n",
startTime, gc_cause, used, committed, max, used_percent,
((used_percent < MIN_USED_PERCENT) ? TestExcessGCLockerCollectionsStringConstants.USED_TOO_LOW
: TestExcessGCLockerCollectionsStringConstants.USED_OK));
}
}
}
} catch (RuntimeException ex) {
System.err.println("Exception during notification processing:" + ex);
ex.printStackTrace();
}
}
public void setCollectionUsageThreshold(long newThreshold) {
if (!isCollectionUsageThresholdSupported()) {
throw new UnsupportedOperationException(
"CollectionUsage threshold is not supported");
}
Util.checkControlAccess();
MemoryUsage usage = getUsage0();
if (newThreshold < 0) {
throw new IllegalArgumentException(
"Invalid threshold: " + newThreshold);
}
if (usage.getMax() != -1 && newThreshold > usage.getMax()) {
throw new IllegalArgumentException(
"Invalid threshold: " + newThreshold +
" > max (" + usage.getMax() + ").");
}
synchronized (this) {
if (!gcSensorRegistered) {
// pass the sensor to VM to begin monitoring
gcSensorRegistered = true;
setPoolCollectionSensor(gcSensor);
}
setCollectionThreshold0(collectionThreshold, newThreshold);
this.collectionThreshold = newThreshold;
}
}
private void logMemoryUsage(StringBuilder sb, MemoryUsage usage, String label) {
// long used, commited;
long init, max;
init = usage.getInit();
// used = usage.getUsed();
// commited = usage.getCommitted();
max = usage.getMax();
// sb.append(label).append(" usage: used ").append(formatBytes(used)) // NOI18N
// .append(" of ").append(formatBytes(commited)); // NOI18N
sb.append(label).append(" usage: initial ").append(formatBytes(init)) // NOI18N
.append(" maximum ").append(formatBytes(max)).append('\n'); // NOI18N
}
public long getTenuredFree()
throws JMException
{
CompositeData data
= (CompositeData) _mbeanServer.getAttribute(getTenuredName(), "Usage");
MemoryUsage usage = MemoryUsage.from(data);
return usage.getMax() - usage.getUsed();
}
public long getEdenFree()
throws JMException
{
CompositeData data
= (CompositeData) _mbeanServer.getAttribute(getEdenName(), "Usage");
MemoryUsage usage = MemoryUsage.from(data);
return usage.getMax() - usage.getUsed();
}
private static void printHeap(long init) {
MemoryUsage heap = mem.getHeapMemoryUsage();
long max = heap.getMax() - init;
long used = heap.getUsed() - init;
long left = max - used;
X.println("Heap left: " + (left / (1024 * 1024)) + "MB");
}
@Override
protected IMonitoringRecord[] createNewMonitoringRecords(final long timestamp, final String hostname, final String vmName,
final IMonitoringController monitoringCtr) {
if (!monitoringCtr.isProbeActivated(SignatureFactory.createJVMMemSignature())) {
return new IMonitoringRecord[] {};
}
final MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
final MemoryUsage heapMemoryUsage = memoryBean.getHeapMemoryUsage();
final MemoryUsage nonHeapMemoryUsage = memoryBean.getNonHeapMemoryUsage();
return new IMonitoringRecord[] { new MemoryRecord(timestamp, hostname, vmName, heapMemoryUsage.getMax(), heapMemoryUsage.getUsed(),
heapMemoryUsage.getCommitted(), heapMemoryUsage.getInit(), nonHeapMemoryUsage.getMax(), nonHeapMemoryUsage.getUsed(),
nonHeapMemoryUsage.getCommitted(), nonHeapMemoryUsage.getInit(), memoryBean.getObjectPendingFinalizationCount()), };
}
public static void createGoodCompositeData() throws Exception {
final int K = 1024;
// these values are synchronized with the item names
final Object[] values = {
new Long(5 * K), // committed
new Long(1 * K), // init
new Long(10 * K), // max
new Long(2 * K), // used
"Dummy",
"Dummy",
};
CompositeType muct =
new CompositeType("MyMemoryUsageCompositeType",
"CompositeType for MemoryUsage",
memoryUsageItemNames,
memoryUsageItemNames,
memoryUsageItemTypes);
CompositeData cd =
new CompositeDataSupport(muct,
memoryUsageItemNames,
values);
MemoryUsage u = MemoryUsage.from(cd);
if (u.getInit() != ((Long) values[INIT]).longValue()) {
throw new RuntimeException("init = " + u.getInit() +
" expected = " + values[INIT]);
}
if (u.getUsed() != ((Long) values[USED]).longValue()) {
throw new RuntimeException("used = " + u.getUsed() +
" expected = " + values[USED]);
}
if (u.getCommitted() != ((Long) values[COMMITTED]).longValue()) {
throw new RuntimeException("committed = " + u.getCommitted() +
" expected = " + values[COMMITTED]);
}
if (u.getMax() != ((Long) values[MAX]).longValue()) {
throw new RuntimeException("max = " + u.getMax() +
" expected = " + values[MAX]);
}
System.out.println(u);
}
public static void createGoodCompositeData() throws Exception {
final int K = 1024;
// these values are synchronized with the item names
final Object[] values = {
new Long(5 * K), // committed
new Long(1 * K), // init
new Long(10 * K), // max
new Long(2 * K), // used
"Dummy",
"Dummy",
};
CompositeType muct =
new CompositeType("MyMemoryUsageCompositeType",
"CompositeType for MemoryUsage",
memoryUsageItemNames,
memoryUsageItemNames,
memoryUsageItemTypes);
CompositeData cd =
new CompositeDataSupport(muct,
memoryUsageItemNames,
values);
MemoryUsage u = MemoryUsage.from(cd);
if (u.getInit() != ((Long) values[INIT]).longValue()) {
throw new RuntimeException("init = " + u.getInit() +
" expected = " + values[INIT]);
}
if (u.getUsed() != ((Long) values[USED]).longValue()) {
throw new RuntimeException("used = " + u.getUsed() +
" expected = " + values[USED]);
}
if (u.getCommitted() != ((Long) values[COMMITTED]).longValue()) {
throw new RuntimeException("committed = " + u.getCommitted() +
" expected = " + values[COMMITTED]);
}
if (u.getMax() != ((Long) values[MAX]).longValue()) {
throw new RuntimeException("max = " + u.getMax() +
" expected = " + values[MAX]);
}
System.out.println(u);
}
/**
* Returns the heap memory used for the current java process.
*/
public static double memoryUsed() throws Exception {
final MemoryUsage heapMemoryUsage = MXBeanHolder.memoryMxBean.getHeapMemoryUsage();
return (double) (heapMemoryUsage.getUsed()) / heapMemoryUsage.getMax();
}
private void setupMemoryListener() {
if (Settings.IMP.MAX_MEMORY_PERCENT < 1 || Settings.IMP.MAX_MEMORY_PERCENT > 99) {
return;
}
try {
final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
final NotificationEmitter ne = (NotificationEmitter) memBean;
ne.addNotificationListener(new NotificationListener() {
@Override
public void handleNotification(final Notification notification, final Object handback) {
final long heapSize = Runtime.getRuntime().totalMemory();
final long heapMaxSize = Runtime.getRuntime().maxMemory();
if (heapSize < heapMaxSize) {
return;
}
MemUtil.memoryLimitedTask();
}
}, null, null);
final List<MemoryPoolMXBean> memPools = ManagementFactory.getMemoryPoolMXBeans();
for (final MemoryPoolMXBean mp : memPools) {
if (mp.isUsageThresholdSupported()) {
final MemoryUsage mu = mp.getUsage();
final long max = mu.getMax();
if (max < 0) {
continue;
}
final long alert = (max * Settings.IMP.MAX_MEMORY_PERCENT) / 100;
mp.setUsageThreshold(alert);
}
}
} catch (Throwable e) {
debug("====== MEMORY LISTENER ERROR ======");
MainUtil.handleError(e, false);
debug("===================================");
debug("FAWE needs access to the JVM memory system:");
debug(" - Change your Java security settings");
debug(" - Disable this with `max-memory-percent: -1`");
debug("===================================");
}
}
private long getMemoryPoolMaxOrCommitted(MemoryPoolMXBean memoryPool) {
MemoryUsage usage = memoryPool.getUsage();
long max = usage.getMax();
return max < 0 ? usage.getCommitted() : max;
}
public Usage(MemoryUsage jmxUsage) {
this(jmxUsage.getUsed(), jmxUsage.getCommitted(), jmxUsage.getMax());
}
public static void createGoodCompositeData() throws Exception {
final int K = 1024;
// these values are synchronized with the item names
final Object[] values = {
new Long(5 * K), // committed
new Long(1 * K), // init
new Long(10 * K), // max
new Long(2 * K), // used
"Dummy",
"Dummy",
};
CompositeType muct =
new CompositeType("MyMemoryUsageCompositeType",
"CompositeType for MemoryUsage",
memoryUsageItemNames,
memoryUsageItemNames,
memoryUsageItemTypes);
CompositeData cd =
new CompositeDataSupport(muct,
memoryUsageItemNames,
values);
MemoryUsage u = MemoryUsage.from(cd);
if (u.getInit() != ((Long) values[INIT]).longValue()) {
throw new RuntimeException("init = " + u.getInit() +
" expected = " + values[INIT]);
}
if (u.getUsed() != ((Long) values[USED]).longValue()) {
throw new RuntimeException("used = " + u.getUsed() +
" expected = " + values[USED]);
}
if (u.getCommitted() != ((Long) values[COMMITTED]).longValue()) {
throw new RuntimeException("committed = " + u.getCommitted() +
" expected = " + values[COMMITTED]);
}
if (u.getMax() != ((Long) values[MAX]).longValue()) {
throw new RuntimeException("max = " + u.getMax() +
" expected = " + values[MAX]);
}
System.out.println(u);
}