I’ve had this method lying around for a few months now
Might not be a smart idea, but I’ve implemented this to run every few seconds.
The only noticeable difference is a 70FPS to 67FPS drop when it manages to clean something forcefully, and it reports back the megabyte’s of allocated memory cleaned.
(No need for pixel arrays / objects to be floating around, once they’re no longer needed execute this method and they’ll hit the road running, leaving you with some memory cleaned :))
Method:
public static void fullGC() {
final long MB = 1024;
final Runtime rt = Runtime.getRuntime();
long isFree = rt.freeMemory();
long wasFree;
do {
wasFree = isFree;
rt.gc();
isFree = rt.freeMemory();
} while (isFree > wasFree);
rt.runFinalization();
if (wasFree > isFree) {
final long mbCleaned = Math.abs((isFree / MB / MB) - (wasFree / MB / MB));
/* Only report back if we've cleaned > 1MB */
if (mbCleaned > 0) {
System.out.println("Managed to clean: "+mbCleaned+"mb.");
}
}
}
Output:
Display Created.
(User re-sizes screen, pixel data increases)
(User restores screen to normal size, extra pixel data now floating around)
Managed to clean: 1mb.
Managed to clean: 2mb.
Managed to clean: 2mb.
Display Disposed.
Hope somebody finds this helpful, I’m use to hearing posts like “No, there’s no way to forcefully garbage collect…”. :point: