3

can someone please explain why the following code causes a memory leak?

Starting from ~27 MB:

# Loops | MB consumption

  • 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);

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

1 Answers1

1

You're not correctly cleaning up the process. This might cause memory leaks. You need to flush both the standard error and standard output as the process runs (possibly in parallel). It's not exactly trivial and the API is not the best.

See for example this or the javadocs for more information.

Finally, let me add that to actually troubleshoot the apparent leak you are better off using a tool like Memory Analyzer which will find potential leaks for you.

Community
  • 1
  • 1
Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94