Suppose I am testing a Java server application. I know how much time it takes to finish the test. Now I'd like to know how much was spent on GC during that test. How can I do it?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
I don't think that is a safe assumption. Are you sure the garbage collector is not working in parallel with your application code?
To measure the time spent in collecting garbage you can query the Garbage Collector MXBean.
Try this:
Another convenient solution is to run
jstat -gc
(documentation) against your process when your tests are done. That will give you nice aggregated output on exactly how much time has been spent in GC during the lifetime of your JVM.Enable garbage collection logs. As documented, you can use
-verbose:gc
,-XX:+PrintGCDetails
and-XX:+PrintGCTimeStamps
flags.-Xloggc
flag can be used to direct those to a file.Resulting logs are human-readable, but for most benefit you probably want them to be run through an analyzer. Such tools are listed in this thread.
This performance metric is recorded by the JVM, and made accessible through JMX. For interactive monitoring, connect to the running JVM with JConsole, and in the "VM Summary" Tab it will say something like:
You can also query JMX programatically.
There are different GC algorithms that behave differently. I recently read a good article on the subject that I can recommend if you'd like to know more.
You can launch your application with the following command line options
-verbose:gc -XX:+PrintGCDateStamps -XX:+PrintGCDetails
and get information about GC.Here's an example of the log message:
Similar to @Steve McLeod's answer that uses ManagementFactory, since Java 8 this can also be written in a single line using Java streams: