Thursday, May 24, 2007

Monitor Memory Usage in Java

There is no "sizeof" in Java. Originally there was no way to check or estimate how much memory has been used in Java. But since Java 1.5, we can use the Monitoring and Management facility to monitor memory usage. The following code

MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();

will print out

init = 0(0K) used = 319360(311K) committed = 2031616(1984K) max = 66650112(65088K)
init = 8585216(8384K) used = 2379416(2323K) committed = 8880128(8672K) max = 100663296(98304K)
MemoryMXBean is also able to send out notification when some memory usage threshold is met.

No comments: