Write a program to create a outOfMemoryException

OutOfMemoryError is thrown when the JVM can’t allocate enough memory to complete the requested action.

To produce these just allocate a bunch of memory in a loop or something similar, but remember to keep your already allocated objects, preferably in a ArrayList or something, or else the garbage collector might reuse the space and free up some memory.

Something like

ArrayList<Object> list = new ArrayList<Object>();

try {
while ( true )
list.add( new Object() );
} catch ( OutOfMemoryError e ) {
// And we are done...

You might want to replace Object with a class that takes up some considerable amount of space, or else this might take some time.

My favorite way to do this is. it uses about 16G memory. (long uses 8B, int_MAX = 2G)

byte[] crasher = new long[Integer.MAX_VALUE];

Linux doesn’t always allocate you all the memory you ask for immediately, since many real applications ask for more than they need. This is called overcommit.

We could also deliberately set the maximum heap size of your JVM to a small amount by using the -Xmx flag.
OutOfMemoryException appears when your heap contains no free space for new objects. Also you should persist references for objects somewhere, otherwise garbage colector takes care about they.

Binary crash (needed amount of bytes doubled on each iteration 🙂

String x = "1";
while (true){
    x = (x + x);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s