I want to gather the heap usage of a program. In particular from a specific start event up to an end event, and with a set interval for example every 10ms. I tried to implement something like this myself, which is the following code. It works for slow intervals, like 1second, but for lower intervals, like 100ms, it becomes buggy. Does the System.gc() method block all threads until it finishes? I'm currently assuming so.
public void startAsync()
{
running = true;
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
while (running)
{
measure();
try
{
Thread.sleep(wait);
} catch (InterruptedException e)
{
throw new RuntimeException();
}
}
}
});
thread.start();
}
public void measure()
{
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
memoryBean.gc();
long currentTime = System.currentTimeMillis();
MemoryUsage memoryUsage = memoryBean.getHeapMemoryUsage();
writer.exec(currentTime - startTime, memoryUsage.getUsed());
}