5
public class MemoryLeakExample {
    public static void main(String[] args) {
        while (true) {
            System.gc();
        }
    }
}

How is memory leaking in this program? Memory is gradualy increasing while monitoring through the NETBEANS profiler. Guide me if am wrong, any help is appreciated. Before 5 min USED HEAP SIZE is :2257416 After: 2258360

Thank you.

Amith
  • 1,907
  • 5
  • 29
  • 48

2 Answers2

11

I ran this code:

final Runtime rt = Runtime.getRuntime();
long before = System.currentTimeMillis();
while (true) {
  System.gc();
  long now = System.currentTimeMillis();
  if (now - before > 1000) {
    System.out.println(rt.totalMemory() + " " + rt.freeMemory());
    before = now;
  }
}

The numbers it prints are totally stable. In your case it is the profiler itself that is occupying memory with profiling data.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • please check with this you will find the difference ` System.out.println("TOTAL "+rt.totalMemory() + " FREE " + rt.freeMemory()+" USED "+(rt.totalMemory() - rt.freeMemory()));` – Amith Nov 22 '12 at 14:08
  • OP : TOTAL 62914560 FREE 62353960 USED 560600 TOTAL 62914560 FREE 62353960 USED 560600 TOTAL 62914560 FREE 62353960 USED 560600 TOTAL 62914560 FREE 62353960 USED 560600 TOTAL 62914560 FREE 62353416 USED 561144 TOTAL 62914560 FREE 62353416 USED 561144 TOTAL 62914560 FREE 62353416 USED 561144 TOTAL 62914560 FREE 62353416 USED 561144 TOTAL 62914560 FREE 62353416 USED 561144 TOTAL 62914560 FREE 62353464 USED 561096 TOTAL 62914560 FREE 62353464 USED 561096 – Amith Nov 22 '12 at 14:09
  • Nope, the numbers are absolutely stable for me. Your case is not that different, either. You have observed a rise of 496 bytes in 10 seconds, which implies hundreds if not thousands of loop iterations. Note that it even subsided a little, so it isn't even steady growth, but a very minor fluctuation. – Marko Topolnik Nov 22 '12 at 14:13
5

Memory is gradualy increasing while monitoring through the NETBEANS profiler.

The VisualVM profiler uses memory to do its profiling. If you perform memory profiling you can see that the memory used is objects sent to the profiler.

If you use a commercial profiler, like YourKit, it records profiling information in native memory so it doesn't impact the heap with what it does.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130