7

I would like to track how much time is spent in GC and how much memory has been collected, but not by analysing GC logs (ie. analyzing what I got from -XX:+PrintGCWhatever).

I found that I can use Sun's ManagementFactory to get a GarbageCollectorMXBean that can give me some GCInfo object containing memory information but I have no guarantee I can collect all GC through this mean.

Does anybody know of a way to do this in code?

insitu
  • 4,488
  • 3
  • 25
  • 42

2 Answers2

4

GarbageCollectorMXBean is the best I've been able to find on the Sun JVM. In my experience, it actually comes pretty close to what you're asking for.

I imagine you could have a dedicated thread that would wake up from time to time to get the GC stats. This would add some determinism to when the stats are collected.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • That's what I found myself. But I am not sure of GCMXbean's behaviour. The doc for getGCInfo() tells it "returns the most recent GCInfo", but not that it returns *all* GCInfo. This may be the case and before trying to figure this out myself, I would be interested in knowing if anyone knows the answer. – insitu Dec 04 '10 at 09:50
  • 1
    BTW, I found this link http://robertmaldon.blogspot.com/2007/09/more-human-friendly-java-gc-timestamps.html that comes pretty close to what I am looking for, but not exactly. – insitu Dec 04 '10 at 09:52
0

Given the range of tools to obtain this information, you are better off using those to analysis your GC behaviour and to optimise for it. e.g. using a memory profiler.

The problem you have is that the information isn't very useful unless it points to a solution to a problem. (Which you can then fix)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 3
    I disagree. As a matter of course, I collect GC stats from within my server apps (which tend to be latency-sensitive so GC is a big deal.) This alerts to the fact that there **is** a problem, for example when the use pattern changes. **Figuring out and fixing** the problem of course then calls for different tools. – NPE Dec 04 '10 at 09:09
  • What I am trying to achieve is something I use from within Java in order to reduce complexity of setup/parsing/analysis. jstat and friends are great, and there exist a lot of 3rd party tools (most of which I am not aware of) that are great, but using it means launching a process, analyze some output. Given all the information comes from the JVM I am running in, one might think there is a way to access this information from within the JVM. – insitu Dec 04 '10 at 10:00