MATLAB: Does MATLAB leak memory when I create Java arrays

javajavarrayleakMATLABmemory

When I create Java arrays in MATLAB, it appears that there is a loss in available memory after the array is cleared. For example, I might execute the following code:
feature memstats
ja = javaArray('javax.swing.JFrame',10000000);
clear all;
feature memstats
The memory statistics shown seem to indicate a loss in physical memory.

Best Answer

This is expected behavior in MATLAB and does not constitute a memory leak. The key point is that the Virtual Memory, or address space, does not change (or changes very little), even before the CLEAR command is issued. This means that the array allocation nets out to almost no change in memory allocation from the application’s point of view. This occurs because the Java heap was already reserved, and this is the space that is used for the Java array.
Although the physical memory used is seen to increase after running the code and the CLEAR command, the memory available to MATLAB is not affected. The use of physical memory and page file memory is managed by the operating system, and it is the effects of this management that result in the apparent loss of physical memory.