When to change settings and when to fix the code
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)When a Java program runs short of memory or pauses too long, there are two kinds of fix: change JVM settings, or change the code. Measurements decide which one, and a bigger heap can never fix a program that keeps objects it no longer needs.
Measure first, change one thing at a time
Measuring first means you collect numbers about the problem before you change any setting: GC logs, how much time goes into GC, how full the heap is after each collection, and the response times users see.
Example 1 · Measuring a job before changing anything
import java.lang.management.GarbageCollectorMXBean;import java.lang.management.ManagementFactory;import java.util.ArrayList;import java.util.List;
public class MeasureDemo { static long gcCount() { long n = 0; for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { n += gc.getCollectionCount(); } return n; }
static long gcTimeMs() { long ms = 0; for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { ms += gc.getCollectionTime(); } return ms; }
// The job we want to measure: build a fee report line for each of 20 lakh students. static long buildReports() { long chars = 0; for (int roll = 1; roll <= 2_000_000; roll++) { List<Integer> fees = new ArrayList<>(); fees.add(45_000 + roll % 1000); fees.add(12_000); String line = "Roll " + roll + " pays Rs " + (fees.get(0) + fees.get(1)); chars += line.length(); } return chars; }
public static void main(String[] args) { long gcBefore = gcCount(); long gcTimeBefore = gcTimeMs(); long start = System.nanoTime();
long chars = buildReports();
long elapsedMs = (System.nanoTime() - start) / 1_000_000; System.out.println("Report characters: " + chars); System.out.println("Time taken: " + elapsedMs + " ms"); System.out.println("GC runs: " + (gcCount() - gcBefore)); System.out.println("Time in GC: " + (gcTimeMs() - gcTimeBefore) + " ms"); }}Report characters: 50888896 Time taken: 240 ms GC runs: 2 Time in GC: 7 ms
What this code does
- The GC MXBeans count how many collections ran and how many milliseconds they took;
System.nanoTime()gives the elapsed time. Read them before and after the work you care about. - Here the job took about 240 ms and GC only 13 ms of it, so GC tuning could save at most about 5%. Your numbers will differ: run it a few times and on realistic data before deciding anything.
Without a baseline you cannot tell whether a change helped, did nothing, or made things worse. A safe routine:
- Write down the symptom: slow pages at 10 am,
OutOfMemoryErrorin the night batch, long pauses. - Turn on GC logs and record a baseline under a realistic load.
- Decide whether the cause is the code (too much live data or garbage) or the settings (too little heap, wrong pause goal).
- Change one thing, run the same load again and compare. Keep the change only if the numbers improved.
More heap hides a leak but does not fix it
A memory leak in Java is data the program no longer needs but still keeps reachable, for example in a static list that only grows. The garbage collector cannot free it, because something still points to it.
Example 2 · A leak: every receipt is kept forever
import java.util.ArrayList;import java.util.List;
public class OrderHistoryDemo { // Bug: every receipt is kept forever, even after the order is delivered. static List<byte[]> receipts = new ArrayList<>();
public static void main(String[] args) { int orders = args.length > 0 ? Integer.parseInt(args[0]) : 40;
for (int order = 1; order <= orders; order++) { receipts.add(new byte[1024 * 1024]); // 1 MB receipt PDF per order for (int i = 0; i < 5_000; i++) { String line = "Order " + order + " item " + i; // short-lived garbage if (line.isEmpty()) { System.out.println("never happens"); } } } System.out.println("Orders handled: " + orders + ", receipts kept: " + receipts.size()); }}Orders handled: 40, receipts kept: 40
What this code does
receiptsis a static list, so every 1 MB receipt stays reachable for as long as the program runs, even after the order is delivered.- With the default 40 orders it finishes fine. The leak only shows when the program handles more orders than the heap can hold, as in the runs below.
Example 3 · A bigger heap only moves the crash
java -Xmx64m OrderHistoryDemo 150java -Xmx512m OrderHistoryDemo 150java -Xmx512m OrderHistoryDemo 400Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at OrderHistoryDemo.main(OrderHistoryDemo.java:12) Orders handled: 150, receipts kept: 150 Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at OrderHistoryDemo.main(OrderHistoryDemo.java:12)
What this code does
- With 64 MB the program fails long before 150 orders. With 512 MB, 150 orders now finish, which looks like a fix, but 400 orders crash again: the leak still grows with every order.
- In G1, each 1 MB array is a humongous object that here needs two 1 MB regions, so the heap fills even faster than the arithmetic suggests. The stack trace line points to where the last allocation failed, not to the cause, which is the static list.
Example 4 · The fix: keep only what the app shows
import java.util.ArrayDeque;import java.util.Deque;
public class OrderHistoryFixedDemo { static final int KEEP = 20; // the app only shows the last 20 receipts static Deque<byte[]> recentReceipts = new ArrayDeque<>();
public static void main(String[] args) { int orders = args.length > 0 ? Integer.parseInt(args[0]) : 40;
for (int order = 1; order <= orders; order++) { recentReceipts.addLast(new byte[1024 * 1024]); // 1 MB receipt PDF per order if (recentReceipts.size() > KEEP) { recentReceipts.removeFirst(); // older receipts become garbage } for (int i = 0; i < 5_000; i++) { String line = "Order " + order + " item " + i; if (line.isEmpty()) { System.out.println("never happens"); } } } System.out.println("Orders handled: " + orders + ", receipts kept: " + recentReceipts.size()); }}Orders handled: 40, receipts kept: 20
What this code does
- The app only ever shows the last 20 receipts, so the fix keeps 20 in an
ArrayDequeand removes the oldest; older receipts become garbage the GC can free. - Run with
-Xmx64mand 1000 orders, it now printsOrders handled: 1000, receipts kept: 20: the memory needed no longer grows with the number of orders.
Raising -Xmx gives the leak more room, so the crash comes later: after a day instead of an hour, or with 400 orders instead of 150. Meanwhile every collection has more live data to scan, and the GC log keeps showing the floor rising. The only real fix is in the code: stop keeping what you no longer need. More heap is the right fix in a different case: when the heap after GC is high but stable. Then the program really needs that much data, for example a college ERP that loads a whole semester's results, and the heap is simply too small for it.
Reduce allocation: boxing, temporary objects and big copies
Allocation is creating new objects on the heap. Every object a program creates must later be found and freed by the GC, so a program that allocates less needs fewer collections and puts less load on the collector.
Example 5 · Boxing: List<Long> against long[]
import java.lang.management.ManagementFactory;import java.util.ArrayList;import java.util.List;
public class BoxingAllocationDemo { // HotSpot-specific bean: it can count the bytes one thread has allocated. static final com.sun.management.ThreadMXBean THREADS = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
static long allocatedSoFar() { return THREADS.getThreadAllocatedBytes(Thread.currentThread().getId()); }
static long boxedTotal(int n) { List<Long> amounts = new ArrayList<>(); // every add boxes a long into a Long for (int i = 0; i < n; i++) { amounts.add((long) (i % 500) + 1000); } long total = 0; for (Long a : amounts) { total += a; } return total; }
static long primitiveTotal(int n) { long[] amounts = new long[n]; // one array, no boxes for (int i = 0; i < n; i++) { amounts[i] = (i % 500) + 1000; } long total = 0; for (long a : amounts) { total += a; } return total; }
public static void main(String[] args) { int n = 1_000_000;
long before = allocatedSoFar(); long t1 = boxedTotal(n); long boxedBytes = allocatedSoFar() - before;
before = allocatedSoFar(); long t2 = primitiveTotal(n); long primitiveBytes = allocatedSoFar() - before;
System.out.println("Totals match: " + (t1 == t2)); System.out.println("List<Long> allocated: " + boxedBytes / (1024 * 1024) + " MB"); System.out.println("long[] allocated: " + primitiveBytes / (1024 * 1024) + " MB"); }}Totals match: true List<Long> allocated: 36 MB long[] allocated: 7 MB
What this code does
getThreadAllocatedBytes(a HotSpot-specific method) reports how many bytes this thread has allocated. Eachaddboxes alonginto a newLongobject, plus the list's growing array.- One million payments cost about 36 MB of allocation as
List<Long>and about 7 MB as onelong[], with the same total. Your exact numbers can differ with the JVM version and settings.
Example 6 · String += and copying lists
import java.lang.management.ManagementFactory;import java.util.ArrayList;import java.util.List;
public class ConcatCopyDemo { static final com.sun.management.ThreadMXBean THREADS = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
static long allocatedKb() { return THREADS.getThreadAllocatedBytes(Thread.currentThread().getId()) / 1024; }
public static void main(String[] args) { List<String> names = new ArrayList<>(); for (int i = 0; i < 5_000; i++) { names.add("Student" + i); }
long before = allocatedKb(); String slow = ""; for (String n : names) { slow += n + ","; // copies the whole text every time } long concatKb = allocatedKb() - before;
before = allocatedKb(); StringBuilder sb = new StringBuilder(); for (String n : names) { sb.append(n).append(','); } String fast = sb.toString(); long builderKb = allocatedKb() - before;
before = allocatedKb(); int copiedTotal = 0; for (int page = 0; page < 50; page++) { List<String> copy = new ArrayList<>(names); // a full copy for every page copiedTotal += copy.get(page).length(); } long copyKb = allocatedKb() - before;
before = allocatedKb(); int viewTotal = 0; for (int page = 0; page < 50; page++) { viewTotal += names.get(page).length(); // read in place, no copy } long noCopyKb = allocatedKb() - before;
System.out.println("Same text: " + slow.equals(fast) + ", same total: " + (copiedTotal == viewTotal)); System.out.println("String += in a loop: " + concatKb + " KB allocated"); System.out.println("StringBuilder: " + builderKb + " KB allocated"); System.out.println("Copy list per page: " + copyKb + " KB allocated"); System.out.println("Read without copying: " + noCopyKb + " KB allocated"); }}Same text: true, same total: true String += in a loop: 142019 KB allocated StringBuilder: 203 KB allocated Copy list per page: 978 KB allocated Read without copying: 0 KB allocated
What this code does
slow += n + ","creates a new, longer string on every pass, copying all the text so far: about 140 MB of allocation for 5,000 names.StringBuilderused about 0.2 MB for the same text.- Copying the list on every page allocated about 1 MB for nothing; reading the needed element in place allocated nothing. Numbers are from one Java 21 run and differ on your machine.
Three habits create most avoidable garbage:
- Boxing:
List<Long>orMap<Integer, Integer>turn each number into a separate object; arrays oflongorintdo not. - Temporary objects in loops:
text += partcopies the whole text each time; oneStringBuildergrows a single buffer. - Big copies: copying a large list or array just to read a part of it; read it in place instead.
Find the bug
Find the wasteful line
Each snippet allocates far more than it needs to. Tap the wasteful line, then check the fix.
Join 5,000 student names into one text.
Round 1 of 3A short list of options for a first job
A few JVM options cover most needs in a first job; the rest of the hundreds of flags are for specialists. A typical start command for a service or batch job looks like this.
java -Xms1g -Xmx1g \ -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=dumps \ "-Xlog:gc*:file=gc-%p.log:time,uptime,level,tags:filecount=5,filesize=20m" \ -jar erp-batch.jar-Xms/-Xmx, or-XX:MaxRAMPercentagein containers: give the heap a size on purpose.-XX:+HeapDumpOnOutOfMemoryErrorwith-XX:HeapDumpPath: on a crash, save a heap dump file (a snapshot of every object in the heap) to find what filled it.-Xlog:gc*:file=...with rotation: keep a GC history you can read after an incident.-XX:+UseZGCor-XX:MaxGCPauseMillis: only when measured pauses are too long;-XX:+ExitOnOutOfMemoryErrorto restart cleanly instead of limping on.
Next step
Check your understanding
12 quick questions