java代码通过端口号找到jvm,并输出GC的伊甸区、幸存者区、老年代的初始空间、已使用空间、已分配空间、最大空间
时间: 2023-07-31 10:08:55 浏览: 128
java获得jvm内存大小
4星 · 用户满意度95%
要实现这个功能,需要使用Java Management Extensions(JMX)API。下面是一个基本的代码示例:
```java
import java.lang.management.ManagementFactory;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import com.sun.management.GarbageCollectorMXBean;
import com.sun.management.GcInfo;
public class GCStatsExample {
public static void main(String[] args) throws Exception {
// 获取当前JVM的MBeanServer连接
MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();
// 获取所有的GC MXBean
ObjectName gcName = new ObjectName("java.lang:type=GarbageCollector,name=*");
java.util.List<GarbageCollectorMXBean> gcBeans = java.util.stream.Collectors.toList(
ManagementFactory.getGarbageCollectorMXBeans().stream()
.filter(bean -> bean instanceof com.sun.management.GarbageCollectorMXBean)
.map(bean -> (com.sun.management.GarbageCollectorMXBean) bean)
.collect(java.util.stream.Collectors.toList())
);
// 输出GC的统计信息
for (GarbageCollectorMXBean gcBean : gcBeans) {
System.out.println(gcBean.getName() + ":");
GcInfo gcInfo = gcBean.getLastGcInfo();
if (gcInfo != null) {
System.out.println(" Eden Space:");
System.out.println(" Initial Space: " + gcInfo.getMemoryUsageBeforeGc().get("PS Eden Space").getInit());
System.out.println(" Used Space: " + gcInfo.getMemoryUsageBeforeGc().get("PS Eden Space").getUsed());
System.out.println(" Committed Space: " + gcInfo.getMemoryUsageBeforeGc().get("PS Eden Space").getCommitted());
System.out.println(" Maximum Space: " + gcInfo.getMemoryUsageBeforeGc().get("PS Eden Space").getMax());
System.out.println(" Survivor Space:");
System.out.println(" Initial Space: " + gcInfo.getMemoryUsageBeforeGc().get("PS Survivor Space").getInit());
System.out.println(" Used Space: " + gcInfo.getMemoryUsageBeforeGc().get("PS Survivor Space").getUsed());
System.out.println(" Committed Space: " + gcInfo.getMemoryUsageBeforeGc().get("PS Survivor Space").getCommitted());
System.out.println(" Maximum Space: " + gcInfo.getMemoryUsageBeforeGc().get("PS Survivor Space").getMax());
System.out.println(" Old Gen:");
System.out.println(" Initial Space: " + gcInfo.getMemoryUsageBeforeGc().get("PS Old Gen").getInit());
System.out.println(" Used Space: " + gcInfo.getMemoryUsageBeforeGc().get("PS Old Gen").getUsed());
System.out.println(" Committed Space: " + gcInfo.getMemoryUsageBeforeGc().get("PS Old Gen").getCommitted());
System.out.println(" Maximum Space: " + gcInfo.getMemoryUsageBeforeGc().get("PS Old Gen").getMax());
}
}
}
}
```
这个代码会输出每个GC的名称以及其对应的伊甸区、幸存者区和老年代的初始空间、已使用空间、已分配空间、最大空间。
阅读全文