0

Programmatically opening and closing files in the Matlab editor results in a memory leak. The following code illustrates the problem:

function TestEditorMemoryLeak(filepaths)
    for i = 1 : numel(filepaths)
        docobj = matlab.desktop.editor.openDocument(filepaths{i});
        disp([num2str(i), ': ', filepaths{i}]);
        pause(0.2);
        docobj.closeNoPrompt();
    end
end

Warning: do not run the above code with a large number of files. Depending on how much Java heap memory is allocated under matlab general settings, it could cause matlab to crash and hang causing loss of command history and matlab settings.

I used the above code on about 1300 files, where each file was not too large - maybe an average of around 50 lines per file. On my system, which has the default 768 MB of Java heap memory allocated, the memory runs out after about a thousand files and matlab hangs badly.

I thought that Java garbage collection might clean up after the function runs, but the 768 MB of memory remains used and never goes back to normal in the Windows task manager.

Increasing the Java heap memory setting appropriately, resolves the issue, but I would like to find a real solution. Is there a way to avoid this memory leak? - For example, a way to tell matlab to clean up every now and then? Would be grateful to anyone who has a solution.

skm
  • 329
  • 2
  • 9
  • If you found a bug in MATLAB, you should tell the MathWorks. They are the ones that can fix it. https://www.mathworks.com/support/servicerequests/reportabug.html – Cris Luengo Sep 09 '22 at 13:16

1 Answers1

1

It may not be a 'memory -leak', There is a difference between used heap and allocated heap.

The JVM may hold the already allocated Memory even if is not used by heap space now.

In your case, the JVM process will hold memory during open files, but will not give it back to OS immediately.

You can check this answer why does this java process not release memory.

Daniel
  • 56
  • 2
  • Nevertheless, once the held memory exceeds the allocated Java heap memory, Matlab hangs and corrupts its command history and settings. One would expect that the application should handle its memory requirements and not burden the user with that job. Only one file is open at any given time and as per the Windows Task Manager the memory remains held permanently (two hours is permanent enough) after the code runs. So I would certainly classify it as as a memory leak, although I'm not sure whether to blame Matlab or the JVM. – skm Sep 11 '22 at 12:26