Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 338
Amith Avatar asked Nov 22 '12 13:11

Amith


2 Answers

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.

like image 80
Marko Topolnik Avatar answered Sep 18 '22 16:09

Marko Topolnik


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.

like image 29
Peter Lawrey Avatar answered Sep 20 '22 16:09

Peter Lawrey