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

4

30

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

I don't care how efficient it is!

Sphene answered 27/10, 2008 at 6:25 Comment(0)
G
32

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.

Gunpoint answered 27/10, 2008 at 7:7 Comment(5)
You are correct (my initial reaction was to monitor from the outside), +1 to you ;)Omniscient
Jon Skeet, hello, can you please tell me how to do the same for C#? in java I would subtract free from total, right? And in C# I only found PrivateMemorySize64 in the Process class, but I assume that only gives total memory, right?Tansey
@paulpaul1076: It would be better to ask a new question for that.Gunpoint
@JonSkeet #29871469Tansey
@JonSkeet looks like the closed it as duplicate already, sorryTansey
O
4

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.)

Omniscient answered 27/10, 2008 at 6:48 Comment(0)
L
4

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

Landreth answered 27/10, 2008 at 7:1 Comment(0)
F
-1

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

Falsecard answered 27/10, 2008 at 7:0 Comment(3)
A prime example of why link-only answers are bad. I suggest you delete it altogether as the other answers provide all the necessary information.Distorted
@Distorted : If you observe carefully, my answer was not a link-only answer. I gave the answer and provided the link for extra information. Please take a look again!Falsecard
I downvoted because your answer contains no explanation other than a dead link. Normally I'd encourage you to add an explanation but the other answers already cover that need.Distorted

© 2022 - 2024 — McMap. All rights reserved.