views:

1090

answers:

4

During execution, how can a java program tell how much memory it is using?

I don't care how efficient it is!

+2  A: 
VonC
Thank you CMS, and thank you whoever upvoted this... considering it was not exactly what the user requested ;)
VonC
A: 

java.lang.Runtime.totalMemory() will give you the required info -- http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html

anjanb
+2  A: 

This won't be exact, but for a rough estimate, just subtract Runtime.getRuntime.freeMemory() from Runtime.getRuntime.totalMemory(). Do that at the begining of the program to get an idea of the JVM's overhead memory usage and at intervals latter on in the execution.

mcjabberz
+6  A: 

VonC's answer is an interactive solution - if you want to know programatically, you can use Runtime.totalMemory() to find out the total amount used by the JVM, and Runtime.freeMemory() to find out how much of that is still available (i.e. it's allocated to the JVM, but not allocated within the JVM - new objects can use this memory).

These are instance methods - use Runtime.getRuntime() to first get the singleton instance.

Jon Skeet
You are correct (my initial reaction was to monitor from the outside), +1 to you ;)
VonC