Pages

JVM & OS Memory check

//src/main/java
package com.java.memory;

import java.lang.management.OperatingSystemMXBean;

public class MemoryInfo {


Runtime runtime= Runtime.getRuntime(); // jvm resource
com.sun.management.OperatingSystemMXBean bean =
(com.sun.management.OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean(); // os resource

// OS memory check
public long getFreeMemory() {
long freeMemory =bean.getFreePhysicalMemorySize();
System.out.println("Free OS Memory: "+ freeMemory);
return freeMemory;
}

public long getAllocatedMemory() {

long allocatedMemory = bean.getTotalPhysicalMemorySize() - bean.getFreePhysicalMemorySize();
System.out.println("Allocated OS Memory: "+allocatedMemory);
return allocatedMemory;
}

public long getMaxMemory() {
long maxMemory=bean.getTotalPhysicalMemorySize();
System.out.println("Max OS Memory: "+maxMemory);
return maxMemory;
}

// JVM memory check
public long getJVMFreeMemory() {
long freeMemory =runtime.freeMemory();
System.out.println("Free JVM  Memory: "+ freeMemory);
return freeMemory;
}

public long getJVMAllocatedMemory() {

long allocatedMemory = runtime.totalMemory();
System.out.println("Allocated JVM Memory: "+allocatedMemory);
return allocatedMemory;
}

public long getJVMMaxMemory() {
long maxMemory=runtime.maxMemory();
System.out.println("Max JVM Memory: "+maxMemory);
return maxMemory;
}

}
//src/main/java
package com.java.memory;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

public class MainClass {
public static void main(String[] args) {


String configLocation="classpath:applicationCTX.xml";

AbstractApplicationContext ctx = new GenericXmlApplicationContext(configLocation);

MemoryInfo memInfo= ctx.getBean("memoryInfo",MemoryInfo.class);

memInfo.getFreeMemory();
memInfo.getJVMFreeMemory();
memInfo.getAllocatedMemory();
memInfo.getJVMAllocatedMemory();
memInfo.getMaxMemory();
memInfo.getJVMMaxMemory();

}

}

//src/main/resources/applicationCTX.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="memoryInfo" class="com.java.memory.MemoryInfo"/>
</beans>


//src/test/java
//Junit Example with memory check

package com.java.memory;

import static org.junit.Assert.*;

import org.junit.Assert;
import org.junit.Test;

public class MemoryInfoTest {

MemoryInfo MI = new MemoryInfo();

@Test
public void test() {
assertNotNull(MI.getFreeMemory());
assertNotNull(MI.getAllocatedMemory());
assertNotNull(MI.getMaxMemory());
assertNotNull(MI.getJVMFreeMemory());
assertNotNull(MI.getJVMAllocatedMemory());
assertNotNull(MI.getJVMMaxMemory());
}

}
Share:

No comments:

Post a Comment

Powered by Blogger.

Popular Posts