Java Heap Cleaner

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'))"

Cite As

Davide Tabarelli (2024). Java Heap Cleaner (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2011b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Find more on Performance and Memory in Help Center and MATLAB Answers

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!


Version Published Release Notes

Update of instructions

Description update

Brief description of java code added.