-1

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.

Jade Tang
  • 321
  • 4
  • 23

2 Answers2

1

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

Arron Cao
  • 416
  • 2
  • 9
1

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:

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 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