-
[java] cpu, memory usage monitoring samplejava/WEB WAS 2021. 8. 27. 11:43728x90반응형
How do I monitor the computer's CPU, memory usage in Java?
java api를 확인해보면 아래 인터페이스를 확인할 수 있습니다.
OperatingSystemMXBean (Monitoring and Management Interface for the Java Platform )
getProcessCpuLoad double getProcessCpuLoad() Returns the "recent cpu usage" for the Java Virtual Machine process. This value is a double in the [0.0,1.0] interval. A value of 0.0 means that none of the CPUs were running threads from the JVM process during
docs.oracle.com
Interface OperatingSystemMXBean 를 활용하면 모니터링 프로그램을 쉽게 만들 수 있습니다.
[주요 메소드]
getSystemCpuLoad() : Returns the "recent cpu usage" for the whole system
getTotalPhysicalMemorySize() : Returns the total amount of physical memory in bytes
getFreePhysicalMemorySize() : Returns the amount of free physical memory in bytes.
아래 코드는 CPU사용률, 메모리 잔여량, 전체 물리메모리량을 확인할 수 있는 코드입니다.
#소스코드
package com.xmpo; import com.sun.management.OperatingSystemMXBean; import java.lang.management.ManagementFactory; public class Monitoring { public static void main(String[] args) { try{ OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class); for(int i=0;i<100;i++){ System.out.println("***********************************************************"); System.out.println("CPU Usage : " + String.format("%.2f", osBean.getSystemCpuLoad() * 100)); System.out.println("Memory Free Space : " + String.format("%.2f", (double)osBean.getFreePhysicalMemorySize()/1024/1024/1024 )); System.out.println("Memory Total Space : " + String.format("%.2f", (double)osBean.getTotalPhysicalMemorySize()/1024/1024/1024 )); Thread.sleep(1000); } }catch (Exception e){ System.out.println(e.toString()); } } }
#출력결과
저 PC 사양이 아래와 같은데요. 전체 메모리를 정확하게 출력해주고 있네요.
아래는 작업관리자에서 확인 할 수 있는 CPU사용률과 메모리 수치와 비교해보았습니다.
사용가능 메모리와 CPU사용률을 비교해보면 거의 동일한 것을 확인 할 수 있습니다.
728x90반응형'java > WEB WAS' 카테고리의 다른 글
톰캣의 lib 실행순서 (4) - 퍼옴 (0) 2021.10.01 [TroubleShooting] 다양한 장애유형 대처방안 (CPU, Resource, Boot) (0) 2021.08.27 서버 반응이 느려질때 - 파일다운로드 느리거나 웹서버 느려질때 (0) 2021.08.25 Jeus 인코딩 문제 해결방법 (0) 2021.08.23 제우스 재기동 (0) 2021.08.20