Is there any way to utilize maximum memory of the system using strings?
I’m using runtime to display the free memory. I’ve tried with this code:
class Mem{
public static void main(String[] args) {
System.out.println(Runtime.getRuntime().maxMemory());
System.out.println(Runtime.getRuntime().totalMemory());
System.out.println(Runtime.getRuntime().freeMemory());
String str=new String("Hi");
for(long i=0;i<1000000;i++){
str+="aa";
//System.out.println(i);
}
System.out.println(Runtime.getRuntime().freeMemory());
}
}
However, the garbage collector comes into action for every few iterations and frees up the memory. Is is possible to make it utilize maximum memory and display the free memory before gc frees it up?
At the end, your string only contains 2 million characters. If you want to make your code run out of memory, change
to
That’ll make the string grow exponentially, and no amount of garbage collection will help even with a modest number of iterations.