2

How can I determine the memory usage for referenced objects only in java? ie. exclude "dead" objects from memory usage during the running of a Java application.

I want to display this information and trigger an alert if it reaches a certain threahold. I also want to use this to measure how much memory is taken up when a file is imported into my application.

My application consists of many processes that all run at the same time of which one of them imports files into memory and then into a database. if I measure memory usage using the Runtime.getRuntime.freeMemory or MemoryPoolMXBean and with all the other processes running, memory usage goes up and up because of these processes and because the GC isn't running "in real time" the memory usage depicts dead objects as well as referenced ones. This is not a clear indication for me as to what is taking up memory at the time.

Is there a way to determine memory used by referenced objects only at any time?

Glen
  • 21
  • 1
  • 1
    Detecting the memory of “live objects” only is as costly as running the garbage collector. And there’s a strong reason why the JVM doesn’t garbage collection all the time but at intervals only. So I suppose there won’t be a satisfying solution for a real application. – Holger Nov 25 '13 at 14:43
  • Thanks for the reply, but it seems that what I am asking for is quite "pie in the sky". I find that memory usage, no matter which memory pool you view (Eden, Survivor, Old Gen), can get very high and if an event is put in place to trigger when the memory does reach a certain threshold, it could be a false alarm because the GC hasn't kicked in yet. – Glen Nov 26 '13 at 06:26
  • Don’t watch for a particular pool, just monitor the committed memory size of [the entire heap](http://docs.oracle.com/javase/7/docs/api/java/lang/management/MemoryMXBean.html#getHeapMemoryUsage()). It is guaranteed that a garbage collection is performed before that amount is raised. So when this value exceeds a threshold (as long as it wasn’t pre-allocated by startup options) you can be sure that it is not a false alarm. – Holger Nov 26 '13 at 08:40

2 Answers2

1

You can look into JConsole and see if that suits your need.
There is also VisualVM.

They let you monitor the app but I am not sure how you can do that in your own application to trigger an alarm once your memory is low.

Also, you can use WeakReference and SoftReference if you want objects to be garbage-collected quicker.

I found a good article on how to query the size of a Java Object. It is slightly long so I cannot post any of it here. However, here is the link: http://www.javamex.com/tutorials/memory/instrumentation.shtml Here is a SO question on the same topic determining java memory usage

Click for:
JConsole
VisualVM

Community
  • 1
  • 1
An SO User
  • 24,612
  • 35
  • 133
  • 221
0

you can use eclipse memory analyzer MAT.

Salah
  • 8,567
  • 3
  • 26
  • 43