Command Palette

Search for a command to run...

Back to the lesson: Topic 14.2 — JVM Memory Areas
Core Java · Example 2 of 3

Heap limits vs native memory

HotSpot rejects an array this long before even looking at the heap size, so the message is the same on every machine. Catching OutOfMemoryError is for the demo only.

A running JVM uses several separate memory areas: one shared heap for objects, one stack per thread for method frames, Metaspace for class metadata, a code cache for JIT-compiled code, and other native memory such as direct buffers and thread stacks. Each has its own limit, its own flag, and its own kind of OutOfMemoryError or StackOverflowError.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a program that recurses until StackOverflowError, catches it, and prints whether a method with more local variables reached a smaller depth than one with fewer (print only the boolean).

02

Show that Integer.valueOf(100) returns the same object every time but new Integer(100)-style allocation (use Integer.valueOf on 1000) does not.

03

Write a program that creates a direct buffer, writes the ints 1 to 4 into it and reads them back, printing the sum.

Explain it without notes

01

Name the JVM's memory areas and what lives in each.

02

Your container keeps getting OOMKilled but the Java logs show no OutOfMemoryError. Why, and what do you do?

03

What changed when Metaspace replaced PermGen in Java 8?

04

Why does a HashMap<Integer, Integer> with a million entries use so much more memory than two int[] arrays of a million?

Heap limits vs native memory
Sign in to run this example in your browser.

Expected output

OutOfMemoryError: Requested array size exceeds VM limit
heap buffer:   direct=false, has byte[]=true
direct buffer: direct=true, has byte[]=false
total capacity: 2048 bytes