This question is well answered by @Eran, @TheLostMind and all, so I am not putting same point, I just want to take the opportunity make a point on how SoftReference and WeakReference helps to "delay" the out of memory exception.
Run below code with JVM arguments as -Xms64m -Xmx64m so that you can see the results quickly.
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class OOM {
public static void main(String[] args) {
System.out.println(new Date());
try {
scenario1(false, false); // in my box, OOM occurred with average of 2 seconds.
//scenario1(true, false); // in my box, OOM occurred average of 6 seconds.
//scenario1(false, true); // in my box, OOM occurred average of 8 seconds.
} catch (Exception e) {
} catch (Error err){
}
System.out.println(new Date());
}
private static void scenario1(boolean useSoftReference, boolean useWeakReference) {
List<Object> list = new ArrayList<>();
while (true) {
for(int i = 0; i < 1000000; i++){
if(useSoftReference){
list.add(new SoftReference<Object>(new Object()));
} else if(useWeakReference){
list.add(new WeakReference<Object>(new Object()));
} else{
list.add(new Object());
}
}
}
}
}