check memory usage - classmexer.jar, class Runtime등 본문

Programming/Java

check memory usage - classmexer.jar, class Runtime등

halatha 2011. 4. 8. 01:24
//	http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html

//	http://www.javamex.com/classmexer
//	source 비공개, agent 방식으로 동작

//	http://www.vogella.de/articles/JavaPerformance/article.html#runtimeinfo_memory
//	http://www.javapractices.com/topic/TopicAction.do?Id=83
/*
	1.	Runtime의 gc()는 API document의 다음 문장을 보면
	The method System.gc() is the conventional and convenient means of invoking this method. 
	결국 System.gc()를 호출하는 것으로 보이는데, 
	Effective Java의 item 7: avoid finalizers를 보면 System.gc, System.funFinalization을
	사용하지 말 것을 권하고 있음
	2.	method 설명을 봐도, MemoryCounter와 비교해봐도
	특정 variable의 사용량을 알아내기 위한 목적으로 사용될 수는 없을 듯
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

public class TestMemoryUsage	{
	private static final long MEGABYTE = 1024L * 1024L;

	public static long bytesToMegabytes(long bytes) {
		return bytes / MEGABYTE;
	}

	public static void main(String[] args) {
		// I assume you will know how to create a object Person yourself...
		List list = new ArrayList();
		for (int i = 0; i <= 10000000; i++) {
			list.add(i);
		}
		// Get the Java runtime
		Runtime runtime = Runtime.getRuntime();
		// Run the garbage collector
		runtime.gc();
		// Calculate the used memory
		long memory = runtime.totalMemory() - runtime.freeMemory();
		System.out.println("Used memory is bytes: " + memory);
		System.out.println("Used memory is megabytes: "
				+ bytesToMegabytes(memory));
		System.out.println("estimated memory size = " + new MemoryCounter().estimate(list));
	}
}
Comments