There are many ways to analyze jvm memory usage offline, like MAT, jmap. However, is there any way to measure the memory usage inside the code during the runtime? Any advice will be much appreciated.
-
What sort of analysis are you interested in performing? Also, which JVM are you using? – templatetypedef Aug 06 '16 at 00:08
-
For example, at some point I wanna know how many object inside the jvm memory like command jmap -heap pid. – Jade Tang Aug 06 '16 at 00:11
-
What specifically do you want to do with this information? – templatetypedef Aug 06 '16 at 00:28
-
actually I want to implement a service with memory threshold controlling policy. If I know a running a thread consuming two much memory then I can terminate it before causing OOM. – Jade Tang Aug 08 '16 at 08:12
2 Answers
Please refer to the official Java documentation, i.e. https://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html
for example:
Runtime.getRuntime().totalMemory() // total memory available
Runtime.getRuntime().freeMemory() // free memory
here is an article that may be helpful

- 416
- 2
- 9
-
Based on the OP's clarification in the comments, I don't think that these tools would actually address their needs. – templatetypedef Aug 06 '16 at 00:26
Any advice will be much appreciated.
Since you have asked for advice .... my advice would be - don't try to do this for anything other than exploring options at development time.
If you were to try to write a program that estimated object sizes and made use of this information to adapt its behavior, you would most likely run into various performance issues, and spend a lot of time figuring out how to avoid them. And your application would be a whole lot more complicated, and harder to maintain.
Another bit of advice: Don't be obsessive about how much space objects are occupying in memory. Unless you have really large data structures, or a very little memory on your platform, saving a few bytes here and there will make little difference.
Having said that, this Q&A covers the topic pretty well:
-
actually I want to implement a service with memory threshold controlling policy. If I know a running a thread consuming two much memory then I can terminate it before causing OOM. – Jade Tang Aug 08 '16 at 08:11
-
I doubt that will work. IMO it would be better to run the code in a separate JVM ... with a limited Heap size. – Stephen C Aug 08 '16 at 11:11
-
vertica - a database by HP, has a feature call resource pool which could control how much memory will available to a query. But I think it is written in C++. – Jade Tang Aug 08 '16 at 12:25