MATLAB Community

MATLAB, community & more

Controlling the Java Heap Size

When you create a Java object from MATLAB, that object will live in the Java heap, whereas workspace variables will go into MATLAB’s main memory. The Java heap space is also shared with MATLAB user interface components, such as figures, the Desktop, and the Editor. You can see in the following example that no size is listed for the java variable, ja:

free = java.lang.Runtime.getRuntime.freeMemory
ja(1,1,1) = java.lang.Double(23);
free = java.lang.Runtime.getRuntime.freeMemory
free =


  Name      Size            Bytes  Class                 Attributes

  free      1x1                 8  double                          
  ja        1x1                    java.lang.Double[]              

free =


Total amount of memory available for Java is set when MATLAB starts up and cannot be changed at run time. However this value can be queried with the following command:

max = java.lang.Runtime.getRuntime.maxMemory
max =


I wrote awhile ago about how MATLAB manages its Java memory (including the distinction between the maximum heap size, the current heap size, and free memory). At the time (MATLAB R2009a) the only way to change the maximum value by creating a java.opts file in your startup directory to set this value with a JVM flag. In the instances where you need more available memory (generally when dealing with Java-intensive toolboxes or managing a lot of really large files), we’ve made it easier in MATLAB R2010a to set this value with panel in the Preferences: File -> Preferences -> General -> Java Heap Memory. No longer do you have to worry about setting JVM flag directly.

MATLAB Java Heap Size Preferences

If you should run out of Java memory, just come to this dialog, and move the slider to the right. You’ll then have to restart MATLAB for the settings to take effect. Note that the default and maximum heap settings vary by platform and processor word-size.

I don’t know the demographics of my readers (beyond the general MATLAB user), but if you’re of my generation, maybe you remember Fraggle Rock? Whenever I hear the word heap, I can’t help but think of the show’s Trash Heap. If you’ve got two minutes to waste, here’s a YouTube video of said Heap.

  • print


To leave a comment, please click here to sign in to your MathWorks Account or create a new one.