Skip to content

Instantly share code, notes, and snippets.

@ben-manes
Last active December 8, 2019 00:32
Show Gist options
  • Save ben-manes/7b42814657465e232d8d to your computer and use it in GitHub Desktop.
Save ben-manes/7b42814657465e232d8d to your computer and use it in GitHub Desktop.
Stresser
import static java.util.concurrent.TimeUnit.SECONDS;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
/**
* A stress test to observe if the cache has a memory leak by not being able to drain the buffers
* fast enough.
*
* @author ben.manes@gmail.com (Ben Manes)
*/
public final class Stresser {
private static final int THREADS = 2 * Runtime.getRuntime().availableProcessors();
private static final long STATUS_INTERVAL = 5;
private static final int LENGTH = (1 << 20);
private static final int MASK = LENGTH - 1;
private final Cache<Integer, Integer> cache;
private final Integer[] ints;
private final long startTime;
public Stresser() {
Executors.newSingleThreadScheduledExecutor()
.scheduleAtFixedRate(this::status, STATUS_INTERVAL, STATUS_INTERVAL, SECONDS);
cache = CacheBuilder.newBuilder()
.maximumSize(LENGTH)
.build();
startTime = System.nanoTime();
ints = new Integer[LENGTH];
Arrays.setAll(ints, key-> {
cache.put(key, key);
return key;
});
status();
}
public void run() throws InterruptedException {
Runnable task = () -> {
int index = ThreadLocalRandom.current().nextInt();
for (;;) {
cache.getIfPresent(ints[index++ & MASK]);
}
};
Executor executor = Executors.newCachedThreadPool();
for (int i = 0; i < THREADS; i++) {
executor.execute(task);
}
}
private void status() {
long allocatedMemory = Runtime.getRuntime().totalMemory();
long freeMemory = Runtime.getRuntime().freeMemory();
long maxMemory = Runtime.getRuntime().maxMemory();
long runningTime = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
String elapsedTime = LocalTime.ofSecondOfDay(runningTime).toString();
System.out.printf("---------- %s ----------%n", elapsedTime);
System.out.printf("Allocated Memory = %,d bytes%n", allocatedMemory);
System.out.printf("Free Memory = %,d bytes%n", freeMemory);
System.out.printf("Max Memory = %,d bytes%n", maxMemory);
System.out.println();
}
public static void main(String[] args) throws Exception {
new Stresser().run();
}
}
@marchino666
Copy link

93.40.229.69 6313

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment