4

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());
}
jpaugh
  • 6,634
  • 4
  • 38
  • 90
KeyboardDrummer
  • 577
  • 5
  • 21

5 Answers5

2

The numbers returned by java.lang.Runtime are not worth much - ignore them.

You'll get better results from the Management API, e.g.

MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getMemoryUsage();

... and related methods, which will likely give you far more information than you ever wanted to know.

skaffman
  • 398,947
  • 96
  • 818
  • 769
2

YourKit is superb (no connection other than as a satisfied customer.)

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Instead of wasting the time in the command prompt, I suggest that you follow the accurate measurements provided by the NetBeans IDE.

wchargin
  • 15,589
  • 12
  • 71
  • 110
0

JProfiler is the best one for monitoring such issues.

Ahmet Karakaya
  • 9,899
  • 23
  • 86
  • 141
0

You can do it from the command line with jmap -heap

http://download.oracle.com/javase/1.5.0/docs/tooldocs/share/jmap.html

1 line script to loop this every x seconds.

bwawok
  • 14,898
  • 7
  • 32
  • 43