Is it possible to do it programmatically?
Here is what I've tried:
import java.util.ArrayList;
import java.util.List;
public class TestMemory {
public static void main(String[] args) {
int kb = 1024;
//Getting the runtime reference from system
Runtime runtime = Runtime.getRuntime();
//Print used memory
System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / kb);
//Print free memory
System.out.println("Free Memory:" + runtime.freeMemory() / kb);
//Print total available memory
System.out.println("Total Memory:" + runtime.totalMemory() / kb);
//Print Maximum available memory
System.out.println("Max Memory:" + runtime.maxMemory() / kb);
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
for (int j = 0; j < 1000; j++) {
list.add("abcdefghij" + i + j);
}
if (i % 1000 == 0) {
try {
Thread.sleep(500);
System.out.println("Free Memory:" + runtime.freeMemory() / kb + " Kb");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
and the output:
Used Memory:289
Free Memory:15582
Total Memory:15872
Max Memory:126720
Free Memory:15405 Kb
Free Memory:22820 Kb (long pause, longer than 500ms and then exception)
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOfRange(Arrays.java:2694)
at java.lang.String.<init>(String.java:203)
at java.lang.StringBuilder.toString(StringBuilder.java:405)
at TestMemory.main(TestMemory.java:32)
It doesn't say to much to me. I expect "Free Memory" value to decrease before the crash. How to write a cycle checking the available memory and informing me about the amount of memory before this exception?