Skip to lesson

Memory areas practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Memory areas become clear once you make them fail on purpose. A tiny -Xss turns deep recursion into a StackOverflowError in seconds, a tiny -Xmx turns a growing list into Java heap space, and a diagram drawn before you run a program tells you exactly what it will print.

Drill 1: draw the memory diagram

A memory diagram is a picture of one moment: frames on the stack, objects on the heap, arrows for references, plus static values. Practise on the library program below at line (*), then compare with Example 2.

  1. Mark the line, and list the calls that are still running at that moment: those are the frames, newest on top.
  2. Write each local variable in its frame: primitives as values, references as arrows.
  3. Draw every object and array once on the heap; two arrows to one box mean one shared object.
  4. Add the static values (with the Class object on the heap) and note objects that do not exist yet.
  5. Predict the output from the picture, then run the program.

Example 1 · A library program to diagram

LibraryTraceDemo.javaJava
class Member {    static int count = 0;    final String name;    final String[] borrowed;           // a reference to an array on the heap
    Member(String name, String[] borrowed) {        this.name = name;        this.borrowed = borrowed;        count++;    }}
public class LibraryTraceDemo {    static String firstBook(Member m) {        String title = m.borrowed[0];        return title.toUpperCase();    // (*) Example 2 draws memory at this line    }
    public static void main(String[] args) {        String[] books = {"Godan", "Malgudi Days"};        Member asha = new Member("Asha", books);        Member same = asha;        books[0] = "Gitanjali";        // changes the array that asha also refers to
        String shout = firstBook(same);        System.out.println(shout);        System.out.println(asha.borrowed[0] + ", members: " + Member.count);    }}
Output
GITANJALI
Gitanjali, members: 1

What this code does

  • asha and same are two references to one Member, and asha.borrowed and books are two references to one array. So books[0] = "Gitanjali" is seen through same.borrowed[0].
  • toUpperCase() creates a new String; the array still holds Gitanjali, so the second line prints it unchanged.

Example 2 · The diagram at line (*)

Text
Memory when line (*) starts in firstBook()  (simplified picture, HotSpot)STACK of thread main (top first)          HEAP+-----------------------------+| firstBook()                 ||   m       ---------------------> Member#1 { name -> "Asha", borrowed -> String[]#1 }|   title   ---------------------> "Gitanjali"+-----------------------------+| main()                      ||   args    ---------------------> String[0]|   books   ---------------------> String[]#1 [ -> "Gitanjali", -> "Malgudi Days" ]|   asha    ---------------------> Member#1|   same    ---------------------> Member#1 (the same object)|   shout   (not assigned yet)|+-----------------------------+Member's Class object (heap): count = 1"GITANJALI" does not exist yet: toUpperCase() creates it when line (*) runs.
In short
Frames alive: firstBook, main.
Heap: 1 Member, 1 String[] of books, args, and the strings.
Two references to Member#1 in main (asha, same) and one in firstBook (m).

What this code does

  • title and books[0] point to the same "Gitanjali" string; nothing was copied. The literal "Godan" is still in the String pool, but the array no longer refers to it.
  • count is 1 because only one new Member(...) ran, however many variables refer to it.

Drill 2: StackOverflowError with a small -Xss

To see a stack fill up, make it small. -Xss256k gives each new thread, including the main thread, a 256 KB stack instead of the default 1 MB (64-bit HotSpot on Windows and Linux).

Example 3 · A recursive nesting checker

NestingDepthDemo.javaJava
public class NestingDepthDemo {    // Returns how deeply the brackets starting at index i are nested (recursive).    static int depth(String s, int i) {        if (i >= s.length() || s.charAt(i) != '[') {            return 0;        }        return 1 + depth(s, i + 1);    }
    public static void main(String[] args) {        int levels = args.length > 0 ? Integer.parseInt(args[0]) : 1000;        String input = "[".repeat(levels) + "]".repeat(levels);   // like deeply nested JSON        System.out.println("Nesting depth: " + depth(input, 0));    }}
Output
Nesting depth: 1000

What this code does

  • depth calls itself once for every [, so the input's nesting decides how many frames are on the stack at once. With no argument it checks 1000 levels.
  • The input string itself, even with 10,000 characters, is a heap object and is no problem. Only the number of frames is limited.

Example 4 · Running it with a smaller stack

Terminal
java NestingDepthDemo 5000java -Xss256k NestingDepthDemo 1000java -Xss256k NestingDepthDemo 5000
Sample output
Nesting depth: 5000
Nesting depth: 1000
Exception in thread "main" java.lang.StackOverflowError
	at NestingDepthDemo.depth(NestingDepthDemo.java:4)
	at NestingDepthDemo.depth(NestingDepthDemo.java:7)
	at NestingDepthDemo.depth(NestingDepthDemo.java:7)
	...

What this code does

  • Real runs on Java 21, Windows. With the default 1 MB stack, 5000 levels fit. With -Xss256k, 1000 levels still fit but 5000 do not.
  • The trace repeats depth(NestingDepthDemo.java:7), the recursive call, so the diagnosis is clear: the stack depth grows with the input. Practice 3 replaces the recursion with a loop.

Recursion that worked before now runs out of frames at a much smaller depth.

The drill is to read the result: the error name says "stack", the repeating line in the trace names the recursive call, and the input size that broke it tells you the depth grows with the input. The real fix is a loop, not a bigger stack.

The exact depth that fits changes between runs and machines, because frame sizes differ between interpreted and JIT-compiled code. Test with a clear margin, such as 1000 versus 5000 levels.

Drill 3: heap OutOfMemoryError with a small -Xmx

To see the heap fill up, make it small. -Xmx16m limits the heap to 16 MB, so a program that keeps every batch of data in a list fails quickly with OutOfMemoryError: Java heap space, while the same program with the default heap finishes.

Example 5 · A college ERP job that loads everything

ErpBatchDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class ErpBatchDemo {    public static void main(String[] args) {        int batches = args.length > 0 ? Integer.parseInt(args[0]) : 10;        List<long[]> loaded = new ArrayList<>();            // the whole college, all at once
        for (int b = 1; b <= batches; b++) {            long[] records = new long[100_000];             // about 800 KB per batch of students            for (int i = 0; i < records.length; i++) {                records[i] = b * 1_000_000L + i;            // fake student record ids            }            loaded.add(records);        }        System.out.println("Batches loaded: " + loaded.size());        System.out.println("Records loaded: " + loaded.size() * 100_000L);    }}
Output
Batches loaded: 10
Records loaded: 1000000

What this code does

  • Each batch is a long[] of 100,000 ids, about 800 KB on the heap, and the loaded list keeps every batch reachable until the end.
  • With the default heap, 10 batches (about 8 MB) are easy. The argument lets you ask for more batches in the next example.

Example 6 · Running it with a smaller heap

Terminal
java ErpBatchDemo 200java -Xmx16m ErpBatchDemo 200
Sample output
Batches loaded: 200
Records loaded: 20000000
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at ErpBatchDemo.main(ErpBatchDemo.java:10)

What this code does

  • Real runs on Java 21. With the default heap (1882 MB on that laptop), 200 batches, about 160 MB, fit. With -Xmx16m the program fails with Java heap space at line 10, where each new batch is created.
  • The error names the heap, and the list that keeps every batch is the reason. Practice 4 keeps only one batch at a time and finishes in 16 MB.

The drill is to ask what keeps the data reachable. Here it is the loaded list: every batch stays in it until the end. Processing one batch at a time and keeping only a summary makes the program work in 16 MB for any number of batches.

Run memory-failure tests in their own JVM with a small -Xmx, never inside a shared test run or on a server: an OutOfMemoryError can break other code that happens to allocate at the same moment.

Drill 4: predict outputs that depend on shared references

Most surprising outputs come from aliasing: two references to one object, where a change through one is seen through the other. Before you run code with arrays, lists or builders, count the new keywords: that is the number of objects.

SharedRowsDemo.javaJava
import java.util.Arrays;
public class SharedRowsDemo {    public static void main(String[] args) {        int[] row = new int[3];        int[][] seats = {row, row, new int[3]};   // rows 0 and 1: the same array object        seats[0][0] = 5;        seats[1][2] = 7;        for (int[] r : seats) {            System.out.println(Arrays.toString(r));        }        System.out.println("rows 0 and 1 same object? " + (seats[0] == seats[1]));    }}
Output
[5, 0, 7]
[5, 0, 7]
[0, 0, 0]
rows 0 and 1 same object? true

Then follow each assignment, which only copies an arrow.

  • Rows 0 and 1 are one array, so seats[0][0] = 5 and seats[1][2] = 7 both land in it and both rows print [5, 0, 7].
  • Row 2 came from its own new int[3], so it stays [0, 0, 0].
  • Collections.nCopies(3, x) and Arrays.fill(array, x) repeat one reference in the same way.

Finish up

Mark complete & continue

Next: What an object looks like in memory