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?
-
1Detecting 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– Holger2013年11月25日 14:43:17 +00:00Commented Nov 25, 2013 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– Glen2013年11月26日 06:26:59 +00:00Commented Nov 26, 2013 at 6:26
-
Don’t watch for a particular pool, just monitor the committed memory size of the entire heap. 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– Holger2013年11月26日 08:40:09 +00:00Commented Nov 26, 2013 at 8:40
2 Answers 2
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
Comments
you can use eclipse memory analyzer MAT.