Skip to content

Instantly share code, notes, and snippets.

@rzymek
Created April 24, 2020 11:06
Show Gist options
  • Save rzymek/14a386a8e1fa4a9faaeded4cb8d5fe3e to your computer and use it in GitHub Desktop.
Save rzymek/14a386a8e1fa4a9faaeded4cb8d5fe3e to your computer and use it in GitHub Desktop.
UsedMemoryMonitor.java
package org.dhatim.fastexcel;
import java.util.concurrent.CompletableFuture;
import static java.lang.String.format;
public class UsedMemoryMonitor<E extends Exception> {
volatile boolean stop = false;
volatile long maxUsedMemoryMB = 0;
public static <E extends Exception> long getMaxMemoryUsedDuring(VoidCallable<E> callable) throws E {
UsedMemoryMonitor monitor = new UsedMemoryMonitor();
callable.call();
monitor.stop = true;
return monitor.maxUsedMemoryMB;
}
private UsedMemoryMonitor() {
CompletableFuture.runAsync(() -> {
long initial = getRuntimeUsedMemoryMB();
while (!stop) {
long used = getRuntimeUsedMemoryMB() - initial;
if(used > maxUsedMemoryMB){
maxUsedMemoryMB = used;
System.out.println(format("max memory used %s MB", maxUsedMemoryMB));
}
sleep(100);
}
});
}
private static void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private static long getRuntimeUsedMemoryMB() {
final long MEGABYTE = 1024L * 1024L;
Runtime runtime = Runtime.getRuntime();
runtime.gc();
return (runtime.totalMemory() - runtime.freeMemory()) / MEGABYTE;
}
@FunctionalInterface
interface VoidCallable<E extends Exception> {
void call() throws E;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment