Amith
Amith

Reputation: 1967

Memory leak in java (in a while loop)

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.

Upvotes: 5

Views: 1753

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200256

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.

Upvotes: 11

Peter Lawrey
Peter Lawrey

Reputation: 533820

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.

Upvotes: 5

Related Questions