2018-08-12 14:03:07 +00:00
|
|
|
package com.boydti.fawe.util;
|
|
|
|
|
|
|
|
import com.boydti.fawe.config.Settings;
|
2019-06-11 20:07:43 +00:00
|
|
|
|
2018-08-12 14:03:07 +00:00
|
|
|
import java.util.Queue;
|
|
|
|
import java.util.concurrent.ConcurrentLinkedQueue;
|
|
|
|
import java.util.concurrent.atomic.AtomicBoolean;
|
|
|
|
|
|
|
|
public class MemUtil {
|
|
|
|
|
|
|
|
private static AtomicBoolean memory = new AtomicBoolean(false);
|
2019-06-11 20:07:43 +00:00
|
|
|
private static Queue<Runnable> memoryLimitedTasks = new ConcurrentLinkedQueue<>();
|
|
|
|
private static Queue<Runnable> memoryPlentifulTasks = new ConcurrentLinkedQueue<>();
|
2018-08-12 14:03:07 +00:00
|
|
|
|
|
|
|
public static boolean isMemoryFree() {
|
|
|
|
return !memory.get();
|
|
|
|
}
|
|
|
|
|
|
|
|
public static boolean isMemoryLimited() {
|
|
|
|
return memory.get();
|
|
|
|
}
|
|
|
|
|
|
|
|
public static boolean isMemoryLimitedSlow() {
|
|
|
|
if (memory.get()) {
|
|
|
|
System.gc();
|
|
|
|
System.gc();
|
|
|
|
calculateMemory();
|
|
|
|
return memory.get();
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static long getUsedBytes() {
|
2019-06-11 20:07:43 +00:00
|
|
|
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
|
2018-08-12 14:03:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public static long getFreeBytes() {
|
|
|
|
return Runtime.getRuntime().maxMemory() - getUsedBytes();
|
|
|
|
}
|
|
|
|
|
|
|
|
public static int calculateMemory() {
|
|
|
|
final long heapSize = Runtime.getRuntime().totalMemory();
|
|
|
|
final long heapMaxSize = Runtime.getRuntime().maxMemory();
|
|
|
|
if (heapSize < heapMaxSize) {
|
|
|
|
return Integer.MAX_VALUE;
|
|
|
|
}
|
|
|
|
final long heapFreeSize = Runtime.getRuntime().freeMemory();
|
|
|
|
final int size = (int) ((heapFreeSize * 100) / heapMaxSize);
|
|
|
|
if (size > (100 - Settings.IMP.MAX_MEMORY_PERCENT)) {
|
|
|
|
memoryPlentifulTask();
|
|
|
|
return Integer.MAX_VALUE;
|
|
|
|
}
|
|
|
|
return size;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void addMemoryLimitedTask(Runnable run) {
|
2019-06-11 20:07:43 +00:00
|
|
|
if (run != null) {
|
2018-08-12 14:03:07 +00:00
|
|
|
memoryLimitedTasks.add(run);
|
2019-06-11 20:07:43 +00:00
|
|
|
}
|
2018-08-12 14:03:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public static void addMemoryPlentifulTask(Runnable run) {
|
2019-06-11 20:07:43 +00:00
|
|
|
if (run != null) {
|
2018-08-12 14:03:07 +00:00
|
|
|
memoryPlentifulTasks.add(run);
|
2019-06-11 20:07:43 +00:00
|
|
|
}
|
2018-08-12 14:03:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public static void memoryLimitedTask() {
|
|
|
|
System.gc();
|
|
|
|
System.gc();
|
|
|
|
for (Runnable task : memoryLimitedTasks) {
|
|
|
|
task.run();
|
|
|
|
}
|
|
|
|
memory.set(true);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void memoryPlentifulTask() {
|
|
|
|
for (Runnable task : memoryPlentifulTasks) {
|
|
|
|
task.run();
|
|
|
|
}
|
|
|
|
memory.set(false);
|
|
|
|
}
|
|
|
|
}
|