Simulate Java
OutOfMemoryError
Here am simulating java OutOfMemoryError, lets discuss
brief details about OutOfMemoryError.
Why OutOfMemoryError
error will arise?
OutOfMemoryError
will arise when allotted Heap size of the Java virtual will be exceeds during
runtime.
Where object will
be saved in Java?
Basically
all java class objects will be saved during runtime in HeapMemory.
Sample Java Program
to simulate OutOfMemoryError
In below program name is object of String, so name
value will be saved to Heap space of JVM.
Calling method1 infinite time will cause
java.lang.OutOfMemoryError: Java heap
space error, because below line
in method1 is causing this error. If you
comments below line you don’t get this error.
name+=";"+name;
package com.blogspot.microtechinfo;
public class JavaOutOfMemory {
private static String name="Marimuthu Rajagopal";
private
static int count=0;
/**
* @param args
*/
public
static void main(String[] args) {
//
TODO Auto-generated method stub
while(true)
{
method1();
}
}
private
static void method1()
{
name+=";"+name;
System.out.println("count="+
++count);
}
}
Output:
when count is 20 i will be getting java.lang.OutOfMemoryError: Java heap
space,It will vary based on machine.
count=1
count=2
count=3
count=4
count=5
count=6
count=7
count=8
count=9
count=10
count=11
count=12
count=13
count=14
count=15
count=16
count=17
count=18
count=19
count=20
Exception in thread "main"
java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOfRange(Unknown Source)
at java.lang.String.(Unknown Source)
at java.lang.StringBuilder.toString(Unknown Source)
at
com.blogspot.microtechinfo.JavaOutOfMemory.method1(JavaOutOfMemory.java:21)
at
com.blogspot.microtechinfo.JavaOutOfMemory.main(JavaOutOfMemory.java:15)
No comments:
Post a Comment