My java version is as below.
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
And my program is very simple. The code is as below.
import java.util.concurrent.ThreadLocalRandom;
public class Test {
static class DummyObj {
public String t1;
public Integer t2;
public Long t3;
public Double t4;
public DummyObj() {
int i = ThreadLocalRandom.current().nextInt(10000);
t1 = "t1t1t1" + i;
t2 = 222 + i;
t3 = 3333L + i;
t4 = 44444.0 + i;
}
}
void f1() {
for (int i=0; i<100; ++i) {
DummyObj t0 = new DummyObj();
if (8 == ThreadLocalRandom.current().nextLong(1000000))
System.out.println(t0.t3);
}
}
public static void main(String... arg) {
Test t0 = new Test();
while (true) {
t0.f1();
try {
Thread.sleep(2L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
I run below command to run this program
javac test.java
java -Xmx8m test
The program always collapse with OutOfMemoryError.
Does anyone know why the gc cannot free the memory?
Beyond that I am making this experiment in order to understand how the Java Garbage Collector works (so this is not some sort of "production code" - it is meant to show the GC "doing its job").