I would like to increase the Java heap size directly by Matlab command because I need dynamic control depending on the environment.
I know the thread How do I increase the heap space for the Java VM in MATLAB 6.0 (R12) and later versions where they say to use java.opts file but I would like to do the same with Matlab prompt directly.
There are many threads that offer to change the parameters only through Matlab GUI or the file, like Matlab's blog post Controlling the Java Heap Size.
I am interested in increasing these parameters dynamically
heapSizeMemoryDefault = 521142272; % 512 MB
assert(java.lang.Runtime.getRuntime.maxMemory > heapSizeMemoryDefault*2, 'Java heap size too small');
runTimeMemoryDefault = 90116624; % about 890 MB
assert(java.lang.Runtime.getRuntime.freeMemory > 90116624*2, 'Java free memory size too small');
How can you increase Java heap size directly in Matlab 2016a?
解决方案
There are a few ways to change java heap size programmatically, but all require Matlab restart, since heap size is allocated at startup.
To query max heap size setting from preferences file:
oldMaxHeapSize = com.mathworks.services.Prefs.getIntegerPref('JavaMemHeapMax'); % MB
Zero result means there is no setting in the preference file yet, which results in some default size allocated.
To set max heap size setting in preferences file:
com.mathworks.services.Prefs.setIntegerPref('JavaMemHeapMax', 2048); % MB
Remember to restart Matlab, e.g. use quit() to end current process. Tested and works on Matlab >= R2013b.
Note that these commands are basically just a programmatic way to edit the matlab.prf file, located in Windows installations at (use correct Matlab version) C:\Users\%USERNAME%\AppData\Roaming\MathWorks\MATLAB\R2013b\matlab.prf
E.g. in this case, we're editing the following setting (you may open the file after you execute the command to check new value is set)
JavaMemHeapMax=I2048
There are plenty of other useful settings in the file which can be queried / set in a similar fashion.