Created
November 13, 2023 16:20
-
-
Save mariofusco/3de5112ac07e22752a4536183c18d520 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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