Skip to content

Instantly share code, notes, and snippets.

@mariofusco
Created November 13, 2023 16:20
Show Gist options
  • Save mariofusco/3de5112ac07e22752a4536183c18d520 to your computer and use it in GitHub Desktop.
Save mariofusco/3de5112ac07e22752a4536183c18d520 to your computer and use it in GitHub Desktop.
package org.drools.ansible.rulebook.integration.api.rulesengine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MemoryMonitor {
private static final Logger LOG = LoggerFactory.getLogger(MemoryMonitor.class.getName());
private static final int DEFAULT_MEMORY_OCCUPATION_PERCENTAGE_THRESHOLD = 90;
private final int memoryOccupationPercentageThreshold;
private final ScheduledThreadPoolExecutor memoryMonitor = new ScheduledThreadPoolExecutor(1, r -> {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
});
MemoryMonitor(long amount, TimeUnit unit) {
this(DEFAULT_MEMORY_OCCUPATION_PERCENTAGE_THRESHOLD, unit.toMillis(amount));
}
MemoryMonitor(int threshold, long period) {
this.memoryOccupationPercentageThreshold = threshold;
memoryMonitor.scheduleAtFixedRate(this::checkMemoryOccupation, period, period, TimeUnit.MILLISECONDS);
}
public void shutdown() {
memoryMonitor.shutdown();
}
protected void checkMemoryOccupation() {
System.gc();
int memoryOccupationPercentage = (int) ((100 * (Runtime.getRuntime().maxMemory() - Runtime.getRuntime().freeMemory())) / Runtime.getRuntime().maxMemory());
if (memoryOccupationPercentage > memoryOccupationPercentageThreshold) {
throw new MemoryThresholdReachedException(memoryOccupationPercentageThreshold, memoryOccupationPercentage);
} else {
LOG.info("Memory occupation is below the threshold: {}%", memoryOccupationPercentageThreshold);
}
}
}
----------------
package org.drools.ansible.rulebook.integration.api.rulesengine;
public class MemoryThresholdReachedException extends RuntimeException {
private final int threshold;
private final int actual;
public MemoryThresholdReachedException(int threshold, int actual) {
this.threshold = threshold;
this.actual = actual;
}
@Override
public String getMessage() {
return "Memory threshold reached: " + actual + "% > " + threshold + "%";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment