java中的内存泄漏(在while循环中)

Ami*_*ith 5 java memory memory-leaks

public class MemoryLeakExample {
    public static void main(String[] args) {
        while (true) {
            System.gc();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如何在这个程序中泄漏内存?通过NETBEANS分析器进行监控时,内存逐渐增加.指导我如果错了,任何帮助表示赞赏. 在5分钟之前USED HEAP SIZE是:2257416之后:2258360

谢谢.

Mar*_*nik 11

我运行了这段代码:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

它打印的数字完全稳定.在您的情况下,分析器本身占用内存并具有分析数据.


Pet*_*rey 5

通过NETBEANS分析器进行监控时,内存逐渐增加.

VisualVM探查器使用内存进行分析.如果执行内存分析,您可以看到使用的内存是发送到分析器的对象.

如果您使用商业分析器(如YourKit),它会将分析信​​息记录在本机内存中,因此它不会影响堆的功能.