Memory usage fixes, general cleanup

This commit is contained in:
Banks Troutman
2019-09-15 19:07:58 -04:00
parent d04096f2c8
commit 0e8029840d
5 changed files with 122 additions and 46 deletions

View File

@@ -0,0 +1,41 @@
package com.chameleonvision;
public class MemoryManager {
private static final long MEGABYTE_FACTOR = 1024L * 1024L;
private int collectionThreshold;
private int lastUsedMb = 0;
public MemoryManager(int collectionThreshold) {
this.collectionThreshold = collectionThreshold;
}
public static long getUsedMemory() {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
public static int getUsedMemoryMB() {
return (int) (getUsedMemory() / MEGABYTE_FACTOR);
}
private static void collect() {
System.gc();
System.runFinalization();
}
public void run() {
var usedMem = getUsedMemoryMB();
if (usedMem != lastUsedMb) {
lastUsedMb = usedMem;
System.out.printf("Memory usage: %dMB\n", usedMem);
}
if (usedMem >= collectionThreshold) {
collect();
System.out.printf("Garbage collected at %dMB\n", usedMem);
}
}
}