Skip to content

Instantly share code, notes, and snippets.

@misTrasteos
Last active December 16, 2021 20:44
Show Gist options
  • Save misTrasteos/e616b87452b215db116448216da59636 to your computer and use it in GitHub Desktop.
Save misTrasteos/e616b87452b215db116448216da59636 to your computer and use it in GitHub Desktop.
Java Stack Allocation Vs Heap Allocation of primitive/object example/test/PoC

Heap Allocation

jbang run https://gist.github.com/misTrasteos/e616b87452b215db116448216da59636\#file-stackorheapallocation-java

You will get a java.lang.OutOfMemoryError: Java heap space. As we are using no-op Epsilon GC and we are allocation plenty of Integer objects in the heap.

Stack Allocation

jbang run -D=PRIMITIVE https://gist.github.com/misTrasteos/e616b87452b215db116448216da59636\#file-stackorheapallocation-java

It will run forever as primitive ints are being created inside the stack and removed after method exit.

///usr/bin/env jbang "$0" "$@" ; exit $?
//JAVA_OPTIONS -Xms2m -Xmx2m
//JAVA_OPTIONS -Xlog:gc*
//JAVA_OPTIONS -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC
//JAVA_OPTIONS -XX:+HeapDumpOnOutOfMemoryError
public class StackOrHeapAllocation {
public static void main(String... args) {
Integer integerObject = null;
int integerPrimitive = -1;
boolean runWithPrimitives = System.getProperty("PRIMITIVE") != null;
while(args.length > -1) // something that returns always true
if(runWithPrimitives)
integerPrimitive = getIntegerPrimitive();
else
integerObject = getIntegerObject();
System.out.println( integerPrimitive );
System.out.println( integerObject );
}
private static Integer getIntegerObject(){
Integer integer = new Integer(0);
return integer;
}
private static int getIntegerPrimitive(){
int integer = 0;
return integer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment