【问题标题】:Java Memory Leak with ScheduledExecutorService带有 ScheduledExecutorService 的 Java 内存泄漏
【发布时间】:2014-03-07 00:46:27
【问题描述】:

谁能解释一下为什么下面的代码会导致内存泄漏?

从 ~27 MB 开始:

# 循环 | MB消耗

  • 400.... | 44
  • 800.... | 60
  • 1200.. | 77
  • 1600.. | 99
  • 2000.. | 99
  • 3000.. | 116,0
  • 4000.. | 116,4
  • 5000.. | 124
// ------------------------------
// executer service     

ScheduledExecutorService $exec = Executors.newSingleThreadScheduledExecutor();   
$exec.scheduleAtFixedRate(new Runnable()
{        
    @Override
    public void run(){

    try{

    Process $p = Runtime.getRuntime().exec("tasklist /fi \"Imagename eq mspaint.exe\"");
    InputStreamReader $ir = new InputStreamReader($p.getInputStream());
    BufferedReader $br = new BufferedReader($ir);

    String $line = $br.readLine();

    while($line != null){
            System.out.println($line);
            $line = $br.readLine();
    }

    $line = null;

    $br.close();
    $br = null;

    $ir.close();
    $ir = null;

    $p = null;

    }catch(IOException $ex){System.out.println("Error" + $ex);}
    }// run() end
} /* runnable object end */, 0, 50, TimeUnit.MILLISECONDS);

// ------------------------------

【问题讨论】:

  • 你确定有内存泄漏吗?你的最大堆大小是多少?你最终会得到OutOfMemoryError吗?
  • 内存消耗增加并不一定意味着内存泄漏...
  • 你为什么要在所有变量名前加上$

标签: java memory memory-leaks scheduledexecutorservice


【解决方案1】:

您没有正确清理进程。这可能会导致内存泄漏。您需要在进程运行时刷新标准错误和标准输出(可能是并行的)。这不是微不足道的,API 也不是最好的。

请参阅例如thisthe javadocs 了解更多信息。

最后,让我补充一点,以实际解决明显的泄漏问题,您最好使用像 Memory Analyzer 这样的工具,它会为您发现潜在的泄漏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 2016-09-29
    相关资源
    最近更新 更多