2019-09-15 19:07:58 -04:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-16 11:45:56 -04:00
|
|
|
public void setCollectionThreshold(int collectionThreshold) {
|
|
|
|
|
this.collectionThreshold = collectionThreshold;
|
|
|
|
|
}
|
2019-09-15 19:07:58 -04:00
|
|
|
|
|
|
|
|
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();
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-16 04:08:23 -04:00
|
|
|
public void run() { run(false); }
|
|
|
|
|
|
|
|
|
|
public void run(boolean print) {
|
2019-09-15 19:07:58 -04:00
|
|
|
var usedMem = getUsedMemoryMB();
|
|
|
|
|
|
|
|
|
|
if (usedMem != lastUsedMb) {
|
|
|
|
|
lastUsedMb = usedMem;
|
2019-09-16 04:08:23 -04:00
|
|
|
if (print) System.out.printf("Memory usage: %dMB\n", usedMem);
|
2019-09-15 19:07:58 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (usedMem >= collectionThreshold) {
|
|
|
|
|
collect();
|
2019-09-16 04:08:23 -04:00
|
|
|
if (print) System.out.printf("Garbage collected at %dMB\n", usedMem);
|
2019-09-15 19:07:58 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|