File Exchange

image thumbnail

Java Heap Cleaner

version (2.33 KB) by Davide Tabarelli
Simple function cleaning up, at runtime, Java heap memory, thus preventing java OutOfMemory error


Updated 23 Apr 2013

View License

Java Heap Cleaner is a MATLAB wrapper for a Java class that cleans up the Java heap from memory leaks, preventing the infamous Java OutOfMemory exception.

The Java code re-initializes some JVM classes responsible for memory leaks, then forcing a garbage collection. Re-initialized Java classes are those used by MATLAB for displaying wievs (command history, current folder etc...).


1) Unpack the archive in [PATH_OF_YOUR_CHOICE]
3) Add [PATH_OF_YOUR_CHOICE]\MatlabGarbageCollector.jar to your static MATLAB classpath.txt file (in MATLAB_ROOT/toolboxes/local/classpath.txt)


Call jheapcl from within your MATLAB code to prevent Java heap memory from completely filling up. The Java Heap Cleaner is very fast and low resouce consuming.

Please consider that there is no general rule about where/when to call jheapcl, it strongly depends on your code and system. You’re encouraged to experiment to find out the best compromise for your setup.

If you like please rate!


Thanks to Pete's for the following comment: 
"For people who don't understand step 3, and/or are getting 'Undefined variable "org" or class' errors, navigate to the appropriate directory and run: javaaddpath(which('MatlabGarbageCollector.jar'))"

Comments and Ratings (26)


I added the suggestion to the code and worked like a charm. Many thanks!


Same question as the previous user. Does the function still work? I am using Matlab2011a

Hello. I would like to ask if this function still works, even in Matlab R2015b.
I tried to add it to my static path and then I simply wrote:
into my code. I have no error, so I suppose it works just fine. But it does not solve my java heap problem. I put it at multiple places in the code but with every iteration it is getting slower and slower and even keeps the original input arguments.

@Robert: to monitor Heap Memory consumption of the Java virtual machine you can use the graphical tool "jvisualvm.exe" that is included in the Java SDK release.

By the way, jheapcl just clean the Heap space, therefore it has no effect if you call it only once, you have to use it when the used heap memory approach the upper limit; this depends on your code and on your matlab settings.

Have a nice day.


@Davide: How would I monitor the heap memory? Is there a way to see it in Activity Monitor? I've set it to the maximum (256 MB) in the MATLAB Preferences but am still running into the Java Heap Memory errors when I'm repeatedly executing long code that generates lots of images (the problem does not occur in the first run but only after 3-4 runs). jheapcl is not preventing the error from happening, even if I execute it in the preamble.


Works. Had to restart MATLAB. I can't get silent mode to work tho :(


Brilliant, seems to work on 2013a. Even works after it has started displaying error messages.


it is still got error when plot several times. And i got not idea if i just type in the jheapcl to call the function?


thank you so much for this! saving me heaps of time..


Thanks so much!

I also had problems with Java memory after running my psychtoolbox script a couple of times. Now I simply run 'jheapcl' at the end of each script and there is no problem anymore.

@ Robert: did you try to monitor your heap memory? Maybe you don't call jheapcl enough often or maybe there is another memory sink somewhere ...


I need to correct myself: I'm still getting the Java heap memory error message, in spite of running jheapcl at the end of the problematic script. Would have been too nice…


Installed the file and added 'javaaddpath(which('~/Documents/MATLAB/jheapcl/jheapcl/MatlabGarbageCollector.jar');' to my startup.m file. No more errors since then, thank you!

Hello, a short comment to to clarify how to set up the java classpath for jheapcl to work: the "javaaddpath" solution is session scoped; if you want the path to be updated across all sessions follow step 3 of instructions and add [PATH_OF_YOUR_CHOICE]\MatlabGarbageCollector.jar to your static MATLAB classpath.txt file (in MATLAB_ROOT/toolboxes/local/classpath.txt) "

Installed this today, and so far so good. I'm just running jheapcl at the end of a psychtoolbox script that was giving Java Heap errors after running a few times in succession.

Regarding the "javaaddpath" solution for step 3 above, it appears that this does not carry across Matlab sessions. There may be a command somewhere to save the Java path; I just put the javaaddpath commands in my startup.m.

Hi pratibha rane, wha is giving you "access denied" can you give me more details?


I added path at the end of classpath.txt, But giving me access denied.Please help


I have the same problem, I've followed the steps but get the below error:

Undefined variable "org" or class "org.dt.matlab.utilities.JavaMemoryCleaner.clear".

Error in jheapcl (line 7)

I'm using Matlab R2011b


Seems good. Couple of points:

typo in the 'silent cleanup' line (1=>0)

For people who don't understand step 3, and/or are getting 'Undefined variable "org" or class' errors, navigate to the appropriate directory and run: javaaddpath(which('MatlabGarbageCollector.jar'))

Yes, David

I unpacked the Jheadcl function in "C:\Program Files\MATLAB\R2009a\toolbox\jheapcl", added this path to the Matlab path by using "File > Set path" and then added "$matlabroot/toolbox/jheapcl/MatlabGarbageCollector.jar" to the last line of the file classpath.txt which is in "C:\Program Files\MATLAB\R2009a\toolbox\local".

However, every now and then, Matlab halts and delivers messages like:

java.lang.OutOfMemoryError: Java heap space
at com.mathworks.jmi.OpaqueJavaInterface.getExceptionMessage(
??? Error using ==> set
Failed to retrieve Exception Message

Exception in thread "Timer-1" java.lang.OutOfMemoryError: Java heap space
at java.lang.String.toLowerCase(Unknown Source)
at Source)
at Source)
at java.util.HashMap.put(Unknown Source)
at com.mathworks.mlwidgets.explorer.control.DocumentContextImpl.getDocumentChanges(
at com.mathworks.mlwidgets.explorer.control.DocumentContextImpl.refreshContents(
at com.mathworks.mlwidgets.explorer.control.RefreshDaemon$
at java.util.TimerThread.mainLoop(Unknown Source)
at Source)

Did I miss something?


Niko, Jorge

did you add the PATH in which you extract the archive to the Matklab Java claspath? See point 3) of the instructions.



Great idea, but I have the same problem:

Undefined variable "org" or class "org.dt.matlab.utilities.JavaMemoryCleaner.clear".

I'm using Matlab 7.8.0 (2009a) and have had problems with memory due to Java heap overflow.
So, I tried to follow your guidelines, but ended up with following error messages. Is it because of my Matlab version?

??? Undefined variable "org" or class

Error in ==> jheapcl at 7



Nice job, it seems really efficient... Could you give more details about what you do in your java class ?


Update of instructions

Description update

Brief description of java code added.

MATLAB Release Compatibility
Created with R2011b
Compatible with any release
Platform Compatibility
Windows macOS Linux