Frankenstein
Frankenstein

Reputation: 693

Java monitor memory usage of unit test

I am trying to store the memory each unit test uses into in a database. So i calculate the free memory before and after the tests with:

Runtime.getRuntime().freeMemory()

If there are garbage collections during the test i count them via:

//returns garbage collection count
private long calculateGarbageCollectionCount(){
    List<GarbageCollectorMXBean> garbageCollectorMXBean = ManagementFactory.getGarbageCollectorMXBeans();
    return garbageCollectorMXBean.get(garbageCollectorMXBean.size()-1).getCollectionCount();
}

Now i need an idea how much memory on average the garbage collections sets free to do something like this:

gcCount*memoryReleased+freeMemoryAtStart-freeMemoryAtEnd

Is there at least a rough estimation how much memory gets release during a garbage collection? I tried using MemoryPoolMXBean with the getPeak method but the value i get is confusing me. Its bigger than the total Memory the JVM has.

Upvotes: 0

Views: 2498

Answers (2)

Frankenstein
Frankenstein

Reputation: 693

Found a useful class that helped: https://github.com/Netflix/spectator/blob/master/spectator-ext-gc/src/main/java/com/netflix/spectator/gc/GcLogger.java

With this class it is possible to catch garbage collection events and more so gather information what happened in them.

As a rough estimation how much memory a unit tests uses i trigger a garbage collection before the start. Calculate the free memory before and after the test and sum up how much memory got released during garbage collections.

Upvotes: 1

GhostCat
GhostCat

Reputation: 140417

Don't try to create your own "profiling application". You should rather choose between:

  1. learning how to "debug" the garbage collector - by understanding the logs the GC can be creating for you. See here for example.
  2. if that "doesn't do" - look into existing tools to help with that. Like visualvm (part of the Oracle JDK) - or even commerical tools such as your kit.

In other words: don't invent your own thing here. Rely on existing, working, robust technology instead.

Upvotes: 2

Related Questions