下面列出了org.springframework.boot.actuate.endpoint.annotation.ReadOperation#java.lang.management.MemoryUsage 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void printMemoryUsage() {
long total = Runtime.getRuntime().totalMemory();
long free = Runtime.getRuntime().freeMemory();
long used = total - free;
System.out.println("Heap size:");
System.out.println("-------------------");
System.out.println("TotalMemory: " + formatSize(total));
System.out.println("UsedMemory: " + formatSize(used));
System.out.println("FreeMemory: " + formatSize(free));
MemoryUsage mu = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
MemoryUsage nmu = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
System.out.println("HeapMemoryUsage: " + mu);
System.out.println("NonHeapMemoryUsage: " + nmu);
}
private final void test() {
System.gc();
MemoryUsagePrinter.printMemoryUsage("init");
allocate();
MemoryUsagePrinter.printMemoryUsage("allocated");
MemoryUsage muFull = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
free();
MemoryUsagePrinter.printMemoryUsage("free");
MemoryUsage muFree = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
assertLessThan(muFree.getCommitted(), muFull.getCommitted(), String.format(
"committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
+ "%s = %s%n%s = %s",
MIN_FREE_RATIO_FLAG_NAME,
ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
MAX_FREE_RATIO_FLAG_NAME,
ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
));
}
public static Map<String, MemoryUsage> getMemoryPoolUsage() {
Map<String, MemoryUsage> gcMemory = new HashMap<String, MemoryUsage>();
for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
String name = memoryPoolMXBean.getName();
if (edenSpace.contains(name)) {
gcMemory.put("eden", memoryPoolMXBean.getUsage());
} else if (survivorSpace.contains(name)) {
gcMemory.put("survivor", memoryPoolMXBean.getUsage());
} else if (oldSpace.contains(name)) {
gcMemory.put("old", memoryPoolMXBean.getUsage());
} else if (permSpace.contains(name)) {
gcMemory.put("perm", memoryPoolMXBean.getUsage());
} else if (codeCacheSpace.contains(name)) {
gcMemory.put("codeCache", memoryPoolMXBean.getUsage());
}
}
return gcMemory;
}
MemoryUsage getCollectMemoryUsage() {
try {
final Map<Object, Object> m = JvmContextFactory.getUserData();
if (m != null) {
final MemoryUsage cached = (MemoryUsage)
m.get(entryCollectMemoryTag);
if (cached != null) {
if (log.isDebugOn())
log.debug("getCollectMemoryUsage",
entryCollectMemoryTag + " found in cache.");
return cached;
}
MemoryUsage u = pool.getCollectionUsage();
if (u == null) u = ZEROS;
m.put(entryCollectMemoryTag,u);
return u;
}
// Should never come here.
// Log error!
log.trace("getCollectMemoryUsage",
"ERROR: should never come here!");
return ZEROS;
} catch (RuntimeException x) {
log.trace("getPeakMemoryUsage",
"Failed to get MemoryUsage: " + x);
log.debug("getPeakMemoryUsage",x);
throw x;
}
}
public static void getVmInfo() throws Exception {
VirtualMachine vm = VirtualMachine.attach(String.valueOf(10248));
// 获得连接地址
Properties properties = vm.getAgentProperties();
String address = (String) properties.get("com.sun.management.jmxremote.localConnectorAddress");
System.out.println(address);
JMXServiceURL url = new JMXServiceURL(address);
JMXConnector connector = JMXConnectorFactory.connect(url);
RuntimeMXBean rmxb = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), "java.lang:type=Runtime", RuntimeMXBean.class);
MemoryMXBean memoryMXBean = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.newPlatformMXBeanProxy(connector.getMBeanServerConnection(), ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
System.out.println(operatingSystemMXBean.getSystemCpuLoad());
MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
Map<String, Object> result = new HashMap<>();
//堆提交内存
result.put("heapCommitedMemory", memoryUsage.getCommitted() / KB);
//当前堆内存
result.put("heapUsedMemory", memoryUsage.getUsed() / KB);
//最大堆大小
result.put("heapMaxMemory", memoryUsage.getMax() / KB);
memoryUsage = memoryMXBean.getNonHeapMemoryUsage();
//非堆提交内存
result.put("nonHeapCommitedMemory", memoryUsage.getCommitted() / KB);
//当前非堆内存
result.put("nonHeapUsedMemory", memoryUsage.getUsed() / KB);
//最大非堆大小
result.put("nonHeapMaxMemory", memoryUsage.getMax() / KB);
System.out.println(result);
vm.detach();
}
public static void getJvmMemPool() {
List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
MemoryUsage usage = memoryPoolMXBean.getUsage();
System.out.println(memoryPoolMXBean.getName() + "\t" + memoryPoolMXBean.getUsage());
}
}
MemoryUsage getHeapMemoryUsage() {
try {
final Map<Object, Object> m = JvmContextFactory.getUserData();
if (m != null) {
final MemoryUsage cached = (MemoryUsage)m.get(heapMemoryTag);
if (cached != null) {
log.debug("getHeapMemoryUsage",
"jvmMemory.getHeapMemoryUsage found in cache.");
return cached;
}
final MemoryUsage u = getMemoryUsage(MemoryType.HEAP);
// getHeapMemoryUsage() never returns null.
//
// if (u == null) u=MemoryUsage.INVALID;
m.put(heapMemoryTag,u);
return u;
}
// Should never come here.
// Log error!
log.trace("getHeapMemoryUsage", "ERROR: should never come here!");
return getMemoryUsage(MemoryType.HEAP);
} catch (RuntimeException x) {
log.trace("getHeapMemoryUsage",
"Failed to get HeapMemoryUsage: " + x);
log.debug("getHeapMemoryUsage",x);
throw x;
}
}
MemoryUsage getPeakMemoryUsage() {
try {
final Map<Object, Object> m = JvmContextFactory.getUserData();
if (m != null) {
final MemoryUsage cached = (MemoryUsage)
m.get(entryPeakMemoryTag);
if (cached != null) {
if (log.isDebugOn())
log.debug("getPeakMemoryUsage",
entryPeakMemoryTag + " found in cache.");
return cached;
}
MemoryUsage u = pool.getPeakUsage();
if (u == null) u = ZEROS;
m.put(entryPeakMemoryTag,u);
return u;
}
// Should never come here.
// Log error!
log.trace("getPeakMemoryUsage", "ERROR: should never come here!");
return ZEROS;
} catch (RuntimeException x) {
log.trace("getPeakMemoryUsage",
"Failed to get MemoryUsage: " + x);
log.debug("getPeakMemoryUsage",x);
throw x;
}
}
MemoryUsage getHeapMemoryUsage() {
try {
final Map<Object, Object> m = JvmContextFactory.getUserData();
if (m != null) {
final MemoryUsage cached = (MemoryUsage)m.get(heapMemoryTag);
if (cached != null) {
log.debug("getHeapMemoryUsage",
"jvmMemory.getHeapMemoryUsage found in cache.");
return cached;
}
final MemoryUsage u = getMemoryUsage(MemoryType.HEAP);
// getHeapMemoryUsage() never returns null.
//
// if (u == null) u=MemoryUsage.INVALID;
m.put(heapMemoryTag,u);
return u;
}
// Should never come here.
// Log error!
log.trace("getHeapMemoryUsage", "ERROR: should never come here!");
return getMemoryUsage(MemoryType.HEAP);
} catch (RuntimeException x) {
log.trace("getHeapMemoryUsage",
"Failed to get HeapMemoryUsage: " + x);
log.debug("getHeapMemoryUsage",x);
throw x;
}
}
private static MemoryData toProto(MemoryUsage usage) {
return MemoryData.newBuilder()
.setUsed(usage.getUsed())
.setCommitted(usage.getCommitted())
.setMax(usage.getMax())
.build();
}
/**
* Format contents of a MemoryUsage object.
* @param name a text prefix used in formatting
* @param usage the MemoryUsage object to format
* @return the formatted contents
*/
private static String formatMemoryUsage(String name, MemoryUsage usage) {
if (usage != null) {
StringBuilder sb = new StringBuilder();
sb.append(INDENT1 + name + " init: " + usage.getInit() + CRLF);
sb.append(INDENT1 + name + " used: " + usage.getUsed() + CRLF);
sb.append(INDENT1 + name + " committed: " + usage.getCommitted() + CRLF);
sb.append(INDENT1 + name + " max: " + usage.getMax() + CRLF);
return sb.toString();
}
return "";
}
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;
}
}
private MemoryUsage getMemoryUsage(MemoryType type) {
if (type == MemoryType.HEAP) {
return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
} else {
return ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
}
}
private static void checkGcInfo(String name, GcInfo info) throws Exception {
System.out.println("GC statistic for : " + name);
System.out.print("GC #" + info.getId());
System.out.print(" start:" + info.getStartTime());
System.out.print(" end:" + info.getEndTime());
System.out.println(" (" + info.getDuration() + "ms)");
Map usage = info.getMemoryUsageBeforeGc();
List pnames = new ArrayList();
for (Iterator iter = usage.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
String poolname = (String) entry.getKey();
pnames.add(poolname);
MemoryUsage busage = (MemoryUsage) entry.getValue();
MemoryUsage ausage = (MemoryUsage) info.getMemoryUsageAfterGc().get(poolname);
if (ausage == null) {
throw new RuntimeException("After Gc Memory does not exist" +
" for " + poolname);
}
System.out.println("Usage for pool " + poolname);
System.out.println(" Before GC: " + busage);
System.out.println(" After GC: " + ausage);
}
// check if memory usage for all memory pools are returned
List pools = ManagementFactory.getMemoryPoolMXBeans();
for (Iterator iter = pools.iterator(); iter.hasNext(); ) {
MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
if (!pnames.contains(p.getName())) {
throw new RuntimeException("GcInfo does not contain " +
"memory usage for pool " + p.getName());
}
}
}
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;
}
}
/**
* Triggers this sensor piggybacking a memory usage object.
* This method sets this sensor on
* and increments the count with the input <tt>increment</tt>.
*/
public void trigger(int increment, MemoryUsage usage) {
synchronized (lock) {
on = true;
count += increment;
// Do something here...
}
triggerAction(usage);
}
/**
* Returns memory usage for the current java process.
*/
public static List<String> memoryUsage() throws Exception {
final MemoryUsage heapMemoryUsage = MXBeanHolder.memoryMxBean.getHeapMemoryUsage();
final MemoryUsage nonHeapMemoryUsage = MXBeanHolder.memoryMxBean.getNonHeapMemoryUsage();
final List<String> memoryUsageList = new LinkedList<>();
memoryUsageList.add("********************************** Memory Usage **********************************"
+ Constants.NEWLINE);
memoryUsageList.add("Heap Memory Usage: " + heapMemoryUsage.toString() + Constants.NEWLINE);
memoryUsageList.add("NonHeap Memory Usage: " + nonHeapMemoryUsage.toString() + Constants.NEWLINE);
return memoryUsageList;
}
public static Map<String, MemoryUsage>
getMemoryUsageAfterGc(CompositeData cd) {
try {
TabularData td = (TabularData) cd.get(MEMORY_USAGE_AFTER_GC);
//return (Map<String,MemoryUsage>)
return cast(memoryUsageMapType.toJavaTypeData(td));
} catch (InvalidObjectException | OpenDataException e) {
// Should never reach here
throw new AssertionError(e);
}
}
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 MemoryUsage getMemoryUsage(MemoryType type) {
if (type == MemoryType.HEAP) {
return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
} else {
return ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
}
}
private Map<String, Object> getMetricsByHost(String host) {
Map<String, Object> metrics = InsertionOrderUtil.newMap();
// JMX client operations for Cassandra.
try (NodeProbe probe = this.newNodeProbe(host)) {
MemoryUsage heapUsage = probe.getHeapMemoryUsage();
metrics.put(MEM_USED, heapUsage.getUsed() / Bytes.MB);
metrics.put(MEM_COMMITED, heapUsage.getCommitted() / Bytes.MB);
metrics.put(MEM_MAX, heapUsage.getMax() / Bytes.MB);
metrics.put(MEM_UNIT, "MB");
metrics.put(DATA_SIZE, probe.getLoadString());
} catch (Throwable e) {
metrics.put(EXCEPTION, e.toString());
}
return metrics;
}
public long getEdenCommitted()
throws JMException
{
CompositeData data
= (CompositeData) _mbeanServer.getAttribute(getEdenName(), "Usage");
MemoryUsage usage = MemoryUsage.from(data);
return usage.getCommitted();
}
MemoryUsage getPeakMemoryUsage() {
try {
final Map<Object, Object> m = JvmContextFactory.getUserData();
if (m != null) {
final MemoryUsage cached = (MemoryUsage)
m.get(entryPeakMemoryTag);
if (cached != null) {
if (log.isDebugOn())
log.debug("getPeakMemoryUsage",
entryPeakMemoryTag + " found in cache.");
return cached;
}
MemoryUsage u = pool.getPeakUsage();
if (u == null) u = ZEROS;
m.put(entryPeakMemoryTag,u);
return u;
}
// Should never come here.
// Log error!
log.trace("getPeakMemoryUsage", "ERROR: should never come here!");
return ZEROS;
} catch (RuntimeException x) {
log.trace("getPeakMemoryUsage",
"Failed to get MemoryUsage: " + x);
log.debug("getPeakMemoryUsage",x);
throw x;
}
}
/** monitor GC, and should the heap grow above 80% usage, clear some strong references */
protected void installGCMonitoring() {
System.out.println("ReferenceManager.installGCMonitoring");
Set<String> ignoredMemoryAreas = new HashSet<>(Arrays.asList("Code Cache", "Compressed Class Space", "Metaspace"));
List<GarbageCollectorMXBean> gcbeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean gcbean : gcbeans) {
NotificationListener listener = (notification, handback) -> {
if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());
//sum up used and max memory across relevant memory areas
long totalMemUsed = 0;
long totalMemMax = 0;
for (Map.Entry<String, MemoryUsage> entry : info.getGcInfo().getMemoryUsageAfterGc().entrySet()) {
String name = entry.getKey();
if (!ignoredMemoryAreas.contains(name)) {
MemoryUsage detail = entry.getValue();
totalMemUsed += detail.getUsed();
totalMemMax += detail.getMax();
}
}
float heapUsageBefore = (float) totalMemUsed / (float) totalMemMax;
if (heapUsageBefore > 0.8) { //TODO make configurable
System.out.println("heap usage (after GC) is " + heapUsageBefore + ", clearing some references");
clearReferences();
}
}
};
NotificationEmitter emitter = (NotificationEmitter) gcbean;
emitter.addNotificationListener(listener, null, null);
}
}
MemoryUsage getCollectMemoryUsage() {
try {
final Map<Object, Object> m = JvmContextFactory.getUserData();
if (m != null) {
final MemoryUsage cached = (MemoryUsage)
m.get(entryCollectMemoryTag);
if (cached != null) {
if (log.isDebugOn())
log.debug("getCollectMemoryUsage",
entryCollectMemoryTag + " found in cache.");
return cached;
}
MemoryUsage u = pool.getCollectionUsage();
if (u == null) u = ZEROS;
m.put(entryCollectMemoryTag,u);
return u;
}
// Should never come here.
// Log error!
log.trace("getCollectMemoryUsage",
"ERROR: should never come here!");
return ZEROS;
} catch (RuntimeException x) {
log.trace("getPeakMemoryUsage",
"Failed to get MemoryUsage: " + x);
log.debug("getPeakMemoryUsage",x);
throw x;
}
}
private static void checkGcInfo(String name, GcInfo info) throws Exception {
System.out.println("GC statistic for : " + name);
System.out.print("GC #" + info.getId());
System.out.print(" start:" + info.getStartTime());
System.out.print(" end:" + info.getEndTime());
System.out.println(" (" + info.getDuration() + "ms)");
Map usage = info.getMemoryUsageBeforeGc();
List pnames = new ArrayList();
for (Iterator iter = usage.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
String poolname = (String) entry.getKey();
pnames.add(poolname);
MemoryUsage busage = (MemoryUsage) entry.getValue();
MemoryUsage ausage = (MemoryUsage) info.getMemoryUsageAfterGc().get(poolname);
if (ausage == null) {
throw new RuntimeException("After Gc Memory does not exist" +
" for " + poolname);
}
System.out.println("Usage for pool " + poolname);
System.out.println(" Before GC: " + busage);
System.out.println(" After GC: " + ausage);
}
// check if memory usage for all memory pools are returned
List pools = ManagementFactory.getMemoryPoolMXBeans();
for (Iterator iter = pools.iterator(); iter.hasNext(); ) {
MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
if (!pnames.contains(p.getName())) {
throw new RuntimeException("GcInfo does not contain " +
"memory usage for pool " + p.getName());
}
}
}
public static void badTypeCompositeData() throws Exception {
final int K = 1024;
final Object[] values = {
new Integer(5 * K),
new Long(1 * K),
new Long(10 * K),
new Long(2 * K),
"Dummy",
"Dummy",
};
CompositeType muct =
new CompositeType("MyMemoryUsageCompositeType",
"CompositeType for MemoryUsage",
memoryUsageItemNames,
memoryUsageItemNames,
badMUItemTypes);
CompositeData cd =
new CompositeDataSupport(muct,
memoryUsageItemNames,
values);
try {
MemoryUsage u = MemoryUsage.from(cd);
} catch (IllegalArgumentException e) {
System.out.println("Expected exception: " +
e.getMessage());
return;
}
throw new RuntimeException(
"IllegalArgumentException not thrown");
}
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;
}
}
public static Map<String, MemoryUsage>
getMemoryUsageBeforeGc(CompositeData cd) {
try {
TabularData td = (TabularData) cd.get(MEMORY_USAGE_BEFORE_GC);
return cast(memoryUsageMapType.toJavaTypeData(td));
} catch (InvalidObjectException | OpenDataException e) {
// Should never reach here
throw new AssertionError(e);
}
}
MemoryUsage getCollectMemoryUsage() {
try {
final Map<Object, Object> m = JvmContextFactory.getUserData();
if (m != null) {
final MemoryUsage cached = (MemoryUsage)
m.get(entryCollectMemoryTag);
if (cached != null) {
if (log.isDebugOn())
log.debug("getCollectMemoryUsage",
entryCollectMemoryTag + " found in cache.");
return cached;
}
MemoryUsage u = pool.getCollectionUsage();
if (u == null) u = ZEROS;
m.put(entryCollectMemoryTag,u);
return u;
}
// Should never come here.
// Log error!
log.trace("getCollectMemoryUsage",
"ERROR: should never come here!");
return ZEROS;
} catch (RuntimeException x) {
log.trace("getPeakMemoryUsage",
"Failed to get MemoryUsage: " + x);
log.debug("getPeakMemoryUsage",x);
throw x;
}
}