Skip to content

Instantly share code, notes, and snippets.

@mattwigway
Created May 19, 2012 06:30
Show Gist options
  • Save mattwigway/2729705 to your computer and use it in GitHub Desktop.
Save mattwigway/2729705 to your computer and use it in GitHub Desktop.
Test of Java memory consumption
/**
* Test memory consumption and garbage collection over time.
* Copyright (C) 2012 Matt Conway. Licensed under the Apache 2 license.
*/
import java.util.ArrayList;
public class MemoryTests {
public static void main (String[] args)
throws InterruptedException {
// don't do this on each iteration
Runtime rt = Runtime.getRuntime();
ArrayList<Integer> arrayList;
short iterations = 0;
double usedMem, totalMem;
// loop until killed
while (true) {
arrayList = getArrayList();
iterations++;
Thread.sleep(500);
if (iterations == 120) {
iterations = 0; // don't let it get filled up
// stackoverflow
totalMem = rt.totalMemory() / 1024;
usedMem = (rt.totalMemory() - rt.freeMemory()) / 1024;
System.out.println(
String.format("%.2f / %.2f KB", usedMem, totalMem)
);
}
}
}
private static ArrayList<Integer> getArrayList () {
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++) {
arrayList.add((Integer) i);
}
return arrayList;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment