Java Increase Memory

The Java memory model specifies how the Java virtual machine works with the computer’s memory (RAM). In this tutorial I will show you how to configure the memory used by Java.

Java Memory Model

The Java memory model used internally in the JVM divides memory between thread stacks and the heap. Each thread running in JVM has its own thread stack. The thread stack contains information about what methods the thread has called to reach the current point of execution. It also contains all local variables for each method being executed.

java memmory model

All local variables of primitive types ( boolean, byte, short, char, int, long, float, double) are fully stored on the thread stack and are thus not visible to other threads.

The heap contains all objects created in your Java application, regardless of what thread created the object. This includes the object versions of the primitive types (e.g. Byte, Integer, Long etc.).

Increase Heap Size

By default the maximum memory used by JVM is lesser than 1/4 of physical memory. You can check the maximum memory by executing following java code:

long maxBytes = Runtime.getRuntime().maxMemory();
System.out.println("Max memory: " + maxBytes / 1024 / 1024 + " MB");

You can configure the memory usage of your java program by setting initial and maximum heap size like this:

java -Xms<initial heap size> -Xmx<maximum heap size>

for example:

java -Xms500m -Xmx6g myprogram

will set the initial heap size to 500 MB and the maximum heap size to 6 GB.

Increase Stack Size

On Windows, the default thread stack size is read from the binary (java.exe). As of Java SE 6, this value is 320k in the 32-bit VM and 1024k in the 64-bit VM. On x86 Solaris/Linux it is 320k in the 32-bit VM and 1024k in the 64-bit VM.

You can increase the stack size by using the Xss argument.

For example:

java -Xss4m myprogram

will set the stack size to 4 MB.

Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+Digg thisPin on PinterestShare on RedditShare on StumbleUponPrint this pageEmail this to someone

Leave a Reply