Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I don't care how efficient it is!

like image 719
Ron Tuffin Avatar asked Oct 27 '08 06:10

Ron Tuffin


People also ask

How do I see how much memory is used in Java?

totalMemory() - Runtime. getRuntime(). freeMemory()) / 1024);

What is memory usage in Java?

A MemoryUsage object represents a snapshot of memory usage. Instances of the MemoryUsage class are usually constructed by methods that are used to obtain memory usage information about individual memory pool of the Java virtual machine or the heap or non-heap memory of the Java virtual machine as a whole.


2 Answers

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.

like image 110
Jon Skeet Avatar answered Oct 15 '22 03:10

Jon Skeet


If you are have a java1.6 somewhere and your program is running in java 1.4.2, 1.5 or 1.6, you can launch a visualVM session, connect to your application, and follow the memory (and much more)

image of monitoring application with Visual VM

(The images are not displayed at the moment, so please refers to Monitoring an application for an illustration.)

like image 22
VonC Avatar answered Oct 15 '22 01:10

VonC