com.alibaba.schedulerx.worker.util.SystemManagementUtil Maven / Gradle / Ivy
package com.alibaba.schedulerx.worker.util;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import com.alibaba.schedulerx.worker.log.LogFactory;
import com.alibaba.schedulerx.worker.log.Logger;
/**
* @author xiaomeng.hxm
*/
public class SystemManagementUtil {
private static final Logger LOGGER = LogFactory.getLogger(SystemManagementUtil.class);
public static String getPid() {
String name = ManagementFactory.getRuntimeMXBean().getName();
return name.split("@")[0];
}
public static float getUsedMemoryPercent() {
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
long totalMemorySize = memoryUsage.getMax();
long usedMemorySize = memoryUsage.getUsed();
float usedRatio = ((float)usedMemorySize) / totalMemorySize;
LOGGER.debug("totalMemorySize:{} MB, usedMemorySize:{} MB, used rate:{}", totalMemorySize / (1024 * 1024),
usedMemorySize / (1024 * 1024), usedRatio);
return usedRatio;
}
public static float getUserDiskSpacePercent() {
File[] files = File.listRoots();
if (files == null) {
return 0f;
}
long freeSpace = 0;
long totalSpace = 0;
float usedRation = 0;
for (File file : files) {
freeSpace += file.getFreeSpace();
totalSpace += file.getTotalSpace();
}
long usedSpace = totalSpace - freeSpace;
if (totalSpace != 0) {
usedRation = ((float) usedSpace) / (float) totalSpace;
}
LOGGER.debug("totalSpace:{} MB, usedSpace:{} MB, used rate:{}", totalSpace / (1024 * 1024),
usedSpace / (1024 * 1024), usedRation);
return usedRation;
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println("pid=" + getPid() + ", cost=" + (System.currentTimeMillis() - start) + "ms");
System.out.println(getUserDiskSpacePercent());
}
}