Java : RunTime Memory Analysis & Garbage Collection

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.

Create a simple Java Class to get JVM Memory Usage & initiated Garbage Collection.


import java.util.logging.Logger;

public class MemoryUsage {
public static final Logger LOGGER = Logger.getLogger(MemoryUsage.class.getName());
private static long currentTime = System.currentTimeMillis() + (1000 * 60 * 5);// 5 minutes

public static void main(String[] args) {
//Take memory print for every 5 minutes
runGarbageCollection();
}
// For every 15 mins run GC
public static void runGarbageCollection() {
if (System.currentTimeMillis() > currentTime) {

Runtime rt = Runtime.getRuntime();

long totalMem = rt.totalMemory();

long maxMem = rt.maxMemory();

long freeMem = rt.freeMemory();

long MB = 1024 * 1024;

long KB = 1024;

LOGGER.severe(" ############## MEMORY MANAGER ##############");

LOGGER.severe("Available Processors : " + rt.availableProcessors());

LOGGER.severe("Total Memory (MB) : " + totalMem / MB);

LOGGER.severe("Max Memory (MB) : " + maxMem / MB);

LOGGER.severe("Available Memory (MB) : " + freeMem / MB);

rt.gc(); // initiated Garbage collection

long freeMemGC = rt.freeMemory();

LOGGER.severe("After GC Available Memory (MB) : " + freeMemGC / MB); //converting KB to MB

if ((freeMemGC - freeMem) > 1024)

LOGGER.severe("Difference in Memory after GC (MB) : "

+ (freeMemGC - freeMem) / MB);

else

LOGGER.severe("Difference in Memory after GC (KB) : "

+ (freeMemGC - freeMem) / KB);

LOGGER.severe(" ############## MEMORY MANAGER ##############");

currentTime = System.currentTimeMillis() + (1000 * 60 * 5);// 5 minutes;

}

}

}

0 comments: