Two versions of the same java program from which you are throwing a memory error and the other is not. Can't find out why?
I wrote a java program that tries to assign 2/3 of the heap memory to a byte array and then assign the remaining 1/3 of the heap to another byte array. I have two versions, one of which is throwing an OutOfMemory error and the other is not. Below are my programs.
Version1 - which throws an OutOfMemory error
public class MemoryTest
{
public static void main(String[] args)
{
System.out.println( Runtime.getRuntime().totalMemory() );
{
byte[] b1 = new byte[(int) (Runtime.getRuntime().maxMemory() * 0.6)];
}
byte[] b2 = new byte[(int) (Runtime.getRuntime().maxMemory() * 0.3)];
System.out.println( Runtime.getRuntime().totalMemory() );
}
}
Version 2 - works fine
public class MemoryTest
{
public static void main(String[] args)
{
System.out.println( Runtime.getRuntime().totalMemory() );
{
byte[] b1 = new byte[(int) (Runtime.getRuntime().maxMemory() * 0.6)];
}
int i=0; //create and initialize which resolves the OutOfMemory issue. No idea how this makes a difference.
byte[] b2 = new byte[(int) (Runtime.getRuntime().maxMemory() * 0.3)];
System.out.println( Runtime.getRuntime().totalMemory() );
}
}
I checked gc and cleared b1 memory during b2 initialization in case of version 2. But the same does not happen with version 1.
I can't seem to find out how int initialization makes a difference? Can someone explain why version 1 is throwing an OutOfMemory error and why version 2 is not?
OS: Windows 7
Java version: 1.8
+3
source to share
No one has answered this question yet
See similar questions:
or similar: