Part 13 / Stage 3
Java internals and performance
Goal: Explain where a running program's data lives (stack vs. heap), what the garbage collector actually does, why
==and.equals()disagree onStrings, what autoboxing costs in a loop, and how to find — and fix — a genuinely slow method instead of guessing. Time: ~5 hours
What you will learn
- Stack vs. heap: method frames vs. objects, and what runs out when each one is exhausted
- The heap in practice: allocation, garbage collection at a conceptual level, and strong vs. weak references
==vs..equals(), theStringpool, and whynew String(...)breaks pooling- Autoboxing: the measured cost of
Integervs.intin a loop, and the small-integer cache - A look under the hood: bytecode (
javap) and the JIT compiler's warm-up - Measuring performance honestly: warm-up, repeats, and what a fair comparison looks like
- Observing a running JVM from the outside with
jcmdandjstat - Putting it together: measure, don't guess — finding and fixing a genuinely slow method with a profiler
About "JDK 21.0.11 Corretto": every command and output below was run on the exact JDK pinned in
../../TOOLING.md. GC log format, exact byte counts and bytecode mnemonics are JDK-internal details — stable across any Java 21 build, but not guaranteed across major versions.
Topics in this part
Practice
Every exercise is one .java file with a public static void main(String[] args) method, the same shape as every example in this part. solutions/ex01.java through ex08.java use a non-public top-level class (class Ex01 { ... }, matching the stage-wide convention from Part 1) so the filename does not need to match the class name. Timings vary by machine and load — where that matters, the exercise prints a boolean check or marks the line (varies), the same style this part's own examples use.
Exercise 1: Stack vs. heap, on purpose
Scenario: Prove to yourself, from inside a running program, that the stack and the heap are separate pools that fail independently. What to do:
- Allocate 1,000,000
"order-" + istrings into anArrayList<String>(each one built at runtime, so none of them are pooled — section 3). Print whetherRuntime.getRuntime().freeMemory()went down across the allocation, and how many labels were built. Drop the only reference afterward. - Write
countDown(n)that calls itself with no base case, catching and rethrowingStackOverflowErrorat every frame on the way back up. Call it, catch the error at the top, and print that it was aStackOverflowError, not anOutOfMemoryError.
Sample output:
== 1. Heap before and after allocating 1,000,000 small objects ==
free heap went down: true
labels built: 1000000
== 2. Recursion with no base case runs out of stack, not heap ==
caught StackOverflowError, not OutOfMemoryError
heap is a completely separate pool from the stack
💡 Hint: freeMemory() is an instantaneous snapshot inside a total that can also grow (totalMemory()) — if the JVM expands the heap mid-allocation, "free went down" is still the right check, not an exact byte count.
Exercise 2: == vs. .equals() on pincodes
Scenario: A delivery app compares pincodes with == in one place and .equals() in another, and the bug only shows up for values built at runtime.
What to do:
- Print
pin1 == pin2andpin1.equals(pin2)for two identical pincode literals. - Print the same two checks for
pin1againstnew String("411001"). intern()thatnew String(...)value and show it now==the original literal.- Build a pincode at runtime by concatenating a variable prefix with a literal suffix, and show it is not
==the literal; then build the same text from two literals only, and show that one is==(compile-time constant folding). - Reassign a
Stringvariable with+, and print whetherSystem.identityHashCodechanged.
Sample output:
== 1. Two literals with the same text share one object ==
pin1 == pin2: true
pin1.equals(pin2): true
== 2. new String(...) always makes a fresh object ==
pin1 == pin3: false
pin1.equals(pin3): true
== 3. intern() returns the pooled reference ==
pin1 == pin4: true
== 4. Built at runtime vs. folded at compile time ==
pin1 == built: false
pin1 == folded: true
== 5. Immutability: every 'change' makes a new object ==
identity changed: true
💡 Hint: javac can only pool text it can prove is a compile-time constant — "4110" + "01" (two literals) qualifies; prefix + "01" (one variable) does not, even though both end up holding the exact same characters at runtime.
Exercise 3: Measuring the cost of autoboxing
Scenario: A reporting job sums 400,000 numbers two ways — a plain int[], and a List<Integer> — and you need the actual, measured cost of boxing, not a guess.
What to do:
- Write
sumPrimitive(n)(builds anint[], sums it) andsumBoxed(n)(builds aList<Integer>, sums it with an unboxing loop). Warm up both 20 times, then time 20 repeats of each. - Print whether both give the same total, the two total times, and whether the boxed version was slower here.
- Show the
Integercache boundary:Integer x = 127, y = 127;compared with==and.equals(), and the same for200.
Sample output (ratio varies by machine):
== 1. Primitive int[] vs. List<Integer>, same values ==
same total either way: true
primitive: 4 ms total (20 repeats, n=400,000)
boxed: 41 ms total
boxed was slower here: true (ratio varies by machine and run)
== 2. The Integer cache boundary ==
127 == 127 (boxed): true
200 == 200 (boxed): false
127 equals 127: true
200 equals 200: true
💡 Hint: Warm up before the timed loop runs, not during it — otherwise the first few timed repeats are secretly paying for JIT compilation that has nothing to do with boxing itself.
Exercise 4: A session cache that cleans itself up
Scenario: A login-session cache must never be the reason a session object stays alive once the user has logged out everywhere else. What to do:
- Create a
LoginSession, take aWeakReferenceto it, and printweak.get()while it's still strongly referenced. - Drop the only strong reference, call
System.gc(), sleep 50 ms, and printweak.get()again. - Put a second
LoginSessioninto aWeakHashMap<LoginSession, String>as a key, print the cache size while it's referenced, drop the only strong reference to that key, retrySystem.gc()+ a short sleep up to 5 times (stopping early once the cache is empty), and print the final cache size.
Sample output:
== 1. A strong reference keeps the session reachable ==
weak.get() while asha still holds it: LoginSession(asha)
== 2. Drop the only strong reference, request a GC, then check again ==
weak.get() after dropping the strong reference and System.gc(): null
== 3. A session cache keyed by WeakHashMap ==
cache size while ravi is referenced: 1
cache size after dropping the only strong reference to the key: 0
💡 Hint: System.gc() is a request, not a guarantee — looping a few times with a short sleep between attempts (and stopping early once the cache is actually empty) makes the demo reliable without depending on exactly when any one collection runs.
Exercise 5: A fair benchmark for CSV building
Scenario: Two ways to build 1,500 CSV rows — += and StringBuilder — and you need a benchmark that's actually fair: warm up first, then time many repeats.
What to do:
- Write
csvConcat(rows)(+=in a loop) andcsvBuilder(rows)(StringBuilder.appendin a loop), both producing identical"R<i>,Pune,1200\n"lines. - Run 200 warm-up repeats of each, discarding the results, then time 200 more repeats of each.
- Print both totals, whether
StringBuilderwas faster, and whether a small sample (5 rows) from both methods is byte-for-byte identical.
Sample output (timings vary by machine):
== Warm-up: 200 repeats of each ==
== Timed: 200 repeats of each, after warm-up ==
concat: 159 ms total (200 repeats, 1500 rows each)
builder: 6 ms total
builder was faster here: true (ratio varies by machine and run)
same output either way: true
💡 Hint: Keep the warm-up and timed loops completely separate — don't fold warm-up iterations into the number you report, or the JIT's compilation cost leaks into your "fair" comparison.
Exercise 6: Watching a real GC pause happen
Scenario: A log importer allocates and drops a fresh buffer 3,000 times in a row — enough short-lived garbage for the collector to actually have to do something. What to do:
- Write a loop of 3,000 rounds, each allocating a fresh
byte[32 * 1024], touching one byte of it, and letting it become unreachable at the end of that round. - Run the program normally and print how many rounds ran.
- Run it again with
-Xlog:gcon the command line (no code change) and note the collector name and at least one pause line it prints.
Sample output:
rounds done, bytes touched: 3000
With -Xlog:gc (an extra line or two, varies by machine):
[0.004s][info][gc] Using G1
[0.019s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 33M->1M(776M) 0.842ms
rounds done, bytes touched: 3000
💡 Hint: The program prints nothing extra on its own — -Xlog:gc is a JVM flag that turns logging on from the outside, the same way jcmd/jstat (README section 7) inspect a process without it changing its own code.
Exercise 7: Find and fix the slow method in a check-in report
Scenario: A conference's check-in desk logs 6,000 badge scans across 3 gates, and wants a list of badges scanned more than once. The obvious method is slow, and you should prove it, not assume it. What to do:
- Write
generateScans(count)with a fixed seed (new Random(7)), a badge pool a quarter the size ofcount(guaranteeing real repeats), and 3 gates. - Write
repeatBadgesSlow(scans): scan a growingseenlist and a growingrepeatslist for every scan (the same shape as the README'srepeatCustomersSlow). - Time it once on its own and print the scan count, repeat-badge count, and the time taken, marked
(varies). - Write
repeatBadgesFast(scans)using aHashMapcount, confirm it gives the identical (sorted) list, then warm up both 20 times and time 20 repeats of each, printing both totals and whether the fix was at least 10x faster.
Sample output (timings vary by machine):
== 1. Time the slow version first ==
Scans: 6000
Repeat badges: 1361
repeatBadgesSlow: 18 ms (varies by machine and run)
== 2. Fix it, then check the answer is identical ==
Same result: true
== 3. Before and after, with warm-up ==
Before (list scan): 269 ms total (20 repeats)
After (HashMap): 2 ms total
at least 10x faster: true (ratio varies by machine and run)
💡 Hint: List.contains is O(n), and both lists in the slow version keep growing — scanning two growing lists for every one of 6,000 scans is the same accidental O(n²) shape as the README's capstone, just with different data.
Exercise 8 (capstone): Two slow methods in one billing report
Scenario: A utility's monthly billing report over 5,000 bills is slow, and this time there isn't just one suspect — profile both candidate methods separately before fixing either. What to do:
- Write
generateBills(count)with a fixed seed, a customer pool a fifth the size ofcount, and 4 cities. - Write
duplicateBillsSlow(bills)(the same growing-two-lists bug as Exercise 7'srepeatBadgesSlow, applied to customer IDs) andsummaryLinesSlow(bills)(+=building one"customer,city,amount\n"line per bill). - Time each of the two slow methods separately and print both times.
- Write
duplicateBillsFast(HashMap count) andsummaryLinesFast(StringBuilder). Confirm both fixed versions give results identical to their slow counterparts. - Warm up all four methods 10 times, then time 10 repeats of each pair, printing both before/after totals and whether each fix was at least 5x faster.
Sample output (timings vary by machine):
== 1. Time each candidate method separately ==
Bills: 5000
duplicateBillsSlow: 11 ms (varies by machine and run)
summaryLinesSlow: 25 ms (varies by machine and run)
both methods are worth fixing: true
== 2. Fix both, then check both answers are identical ==
duplicates match: true
summaries match: true
== 3. Before and after, with warm-up ==
duplicateBills before/after: 67 ms / 1 ms total (10 repeats)
summaryLines before/after: 93 ms / 3 ms total
duplicateBills at least 5x faster: true (varies)
summaryLines at least 5x faster: true (varies)
💡 Hint: Measuring both candidates before touching any code is the point of this exercise — a report with two slow-looking methods doesn't mean both are equally worth fixing, and the only way to know is to time them separately, exactly as the README's "measure, don't guess" rule says.
Show the solutions for Part 13 (8 files)
solutions/ex01.java
// Exercise 1: stack vs heap -- a deliberate StackOverflowError, and the heap
// moving as objects are allocated, reported with Runtime.
class Ex01 {
static int countDown(int n) {
try {
return countDown(n - 1);
} catch (StackOverflowError error) {
throw error; // every earlier frame also sees and rethrows the same error on the way back up
}
}
public static void main(String[] args) {
System.out.println("== 1. Heap before and after allocating 1,000,000 small objects ==");
Runtime runtime = Runtime.getRuntime();
long freeBefore = runtime.freeMemory();
java.util.List<String> labels = new java.util.ArrayList<>();
for (int i = 0; i < 1_000_000; i++) {
labels.add("order-" + i); // each one a fresh, non-pooled String
}
long freeAfter = runtime.freeMemory();
System.out.println("free heap went down: " + (freeAfter < freeBefore));
System.out.println("labels built: " + labels.size());
labels = null; // drop the only reference
System.out.println();
System.out.println("== 2. Recursion with no base case runs out of stack, not heap ==");
try {
countDown(0);
} catch (StackOverflowError error) {
System.out.println("caught StackOverflowError, not OutOfMemoryError");
System.out.println("heap is a completely separate pool from the stack");
}
}
}
solutions/ex02.java
// Exercise 2: == vs equals, the String pool, intern(), and compile-time
// constant folding -- with pincodes instead of city names.
class Ex02 {
public static void main(String[] args) {
System.out.println("== 1. Two literals with the same text share one object ==");
String pin1 = "411001";
String pin2 = "411001";
System.out.println("pin1 == pin2: " + (pin1 == pin2));
System.out.println("pin1.equals(pin2): " + pin1.equals(pin2));
System.out.println();
System.out.println("== 2. new String(...) always makes a fresh object ==");
String pin3 = new String("411001");
System.out.println("pin1 == pin3: " + (pin1 == pin3));
System.out.println("pin1.equals(pin3): " + pin1.equals(pin3));
System.out.println();
System.out.println("== 3. intern() returns the pooled reference ==");
String pin4 = pin3.intern();
System.out.println("pin1 == pin4: " + (pin1 == pin4));
System.out.println();
System.out.println("== 4. Built at runtime vs. folded at compile time ==");
String prefix = "4110";
String built = prefix + "01"; // built at runtime: not auto-pooled
System.out.println("pin1 == built: " + (pin1 == built));
String folded = "4110" + "01"; // both literals: javac folds this to "411001" itself
System.out.println("pin1 == folded: " + (pin1 == folded));
System.out.println();
System.out.println("== 5. Immutability: every 'change' makes a new object ==");
String code = "ORD";
int before = System.identityHashCode(code);
code = code + "-2001";
int after = System.identityHashCode(code);
System.out.println("identity changed: " + (before != after));
}
}
solutions/ex03.java
// Exercise 3: measure a primitive int[] sum vs. a List<Integer> sum of the
// same values, and demonstrate the small-integer cache's == trap.
import java.util.ArrayList;
import java.util.List;
class Ex03 {
static long sumPrimitive(int n) {
int[] values = new int[n];
for (int i = 0; i < n; i++) values[i] = i;
long total = 0;
for (int v : values) total += v;
return total;
}
static long sumBoxed(int n) {
List<Integer> values = new ArrayList<>();
for (int i = 0; i < n; i++) values.add(i);
long total = 0;
for (Integer v : values) total += v;
return total;
}
static long timeIt(java.util.function.LongSupplier fn, int repeats) {
long start = System.nanoTime();
long sink = 0;
for (int r = 0; r < repeats; r++) sink += fn.getAsLong();
if (sink == Long.MIN_VALUE) throw new AssertionError();
return System.nanoTime() - start;
}
public static void main(String[] args) {
int n = 400_000;
int warmup = 20;
int timed = 20;
System.out.println("== 1. Primitive int[] vs. List<Integer>, same values ==");
for (int i = 0; i < warmup; i++) {
sumPrimitive(n);
sumBoxed(n);
}
long primitiveNanos = timeIt(() -> sumPrimitive(n), timed);
long boxedNanos = timeIt(() -> sumBoxed(n), timed);
System.out.println("same total either way: " + (sumPrimitive(n) == sumBoxed(n)));
System.out.printf("primitive: %,d ms total (%d repeats, n=%,d)%n", primitiveNanos / 1_000_000, timed, n);
System.out.printf("boxed: %,d ms total%n", boxedNanos / 1_000_000);
System.out.println("boxed was slower here: " + (boxedNanos > primitiveNanos) + " (ratio varies by machine and run)");
System.out.println();
System.out.println("== 2. The Integer cache boundary ==");
Integer x = 127, y = 127;
Integer p = 200, q = 200;
System.out.println("127 == 127 (boxed): " + (x == y));
System.out.println("200 == 200 (boxed): " + (p == q));
System.out.println("127 equals 127: " + x.equals(y));
System.out.println("200 equals 200: " + p.equals(q));
}
}
solutions/ex04.java
// Exercise 4: a login-session cache built on WeakHashMap, so entries vanish
// on their own once nothing outside the cache references the key any more.
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
class Ex04 {
static class LoginSession {
final String user;
LoginSession(String user) { this.user = user; }
@Override public String toString() { return "LoginSession(" + user + ")"; }
}
public static void main(String[] args) throws InterruptedException {
System.out.println("== 1. A strong reference keeps the session reachable ==");
LoginSession asha = new LoginSession("asha");
WeakReference<LoginSession> weak = new WeakReference<>(asha);
System.out.println("weak.get() while asha still holds it: " + weak.get());
System.out.println();
System.out.println("== 2. Drop the only strong reference, request a GC, then check again ==");
asha = null;
System.gc();
Thread.sleep(50);
System.out.println("weak.get() after dropping the strong reference and System.gc(): " + weak.get());
System.out.println();
System.out.println("== 3. A session cache keyed by WeakHashMap ==");
WeakHashMap<LoginSession, String> cache = new WeakHashMap<>();
LoginSession ravi = new LoginSession("ravi");
cache.put(ravi, "cart: 2 items");
System.out.println("cache size while ravi is referenced: " + cache.size());
ravi = null;
for (int i = 0; i < 5; i++) {
System.gc();
Thread.sleep(50);
if (cache.isEmpty()) break;
}
System.out.println("cache size after dropping the only strong reference to the key: " + cache.size());
}
}
solutions/ex05.java
// Exercise 5: a fair benchmark -- warm up, then time many repeats -- comparing
// string concatenation vs. StringBuilder for building CSV rows.
class Ex05 {
static String csvConcat(int rows) {
String out = "";
for (int i = 0; i < rows; i++) {
out += "R" + i + ",Pune,1200\n";
}
return out;
}
static String csvBuilder(int rows) {
StringBuilder out = new StringBuilder();
for (int i = 0; i < rows; i++) {
out.append("R").append(i).append(",Pune,1200\n");
}
return out.toString();
}
static long timeOnce(java.util.function.IntFunction<String> fn, int rows, int repeats) {
long start = System.nanoTime();
int totalLength = 0;
for (int r = 0; r < repeats; r++) {
totalLength += fn.apply(rows).length();
}
if (totalLength < 0) throw new AssertionError();
return System.nanoTime() - start;
}
public static void main(String[] args) {
int rows = 1_500;
int warmupRepeats = 200;
int timedRepeats = 200;
System.out.println("== Warm-up: " + warmupRepeats + " repeats of each ==");
timeOnce(Ex05::csvConcat, rows, warmupRepeats);
timeOnce(Ex05::csvBuilder, rows, warmupRepeats);
System.out.println("== Timed: " + timedRepeats + " repeats of each, after warm-up ==");
long concatNanos = timeOnce(Ex05::csvConcat, rows, timedRepeats);
long builderNanos = timeOnce(Ex05::csvBuilder, rows, timedRepeats);
System.out.printf("concat: %,d ms total (%d repeats, %d rows each)%n", concatNanos / 1_000_000, timedRepeats, rows);
System.out.printf("builder: %,d ms total%n", builderNanos / 1_000_000);
System.out.println("builder was faster here: " + (builderNanos < concatNanos) + " (ratio varies by machine and run)");
System.out.println("same output either way: " + csvConcat(5).equals(csvBuilder(5)));
}
}
solutions/ex06.java
// Exercise 6: generate enough short-lived garbage for a real GC pause to show
// up under -Xlog:gc, run from the terminal (not something the program itself does).
class Ex06 {
public static void main(String[] args) {
long kept = 0;
for (int round = 0; round < 3_000; round++) {
byte[] receipt = new byte[32 * 1024]; // a fresh 32 KiB array every round
receipt[0] = 1;
kept += receipt[0]; // nothing keeps `receipt` alive past this round
}
System.out.println("rounds done, bytes touched: " + kept);
}
}
solutions/ex07.java
// Exercise 7: find and fix the slow method in a conference check-in desk's
// "repeat scan" report -- measure, don't guess.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
class Ex07 {
record Scan(String badgeId, String gate) {}
static final String[] GATES = {"Gate-A", "Gate-B", "Gate-C"};
static List<Scan> generateScans(int count) {
Random rng = new Random(7); // fixed seed: same data every run
int badgePoolSize = count / 4; // guarantees real repeats
List<Scan> scans = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
String badge = "B-" + rng.nextInt(badgePoolSize);
String gate = GATES[rng.nextInt(GATES.length)];
scans.add(new Scan(badge, gate));
}
return scans;
}
// The bug: for every scan, scan the growing `seen` list AND the growing `repeats` list.
static List<String> repeatBadgesSlow(List<Scan> scans) {
List<String> seen = new ArrayList<>();
List<String> repeats = new ArrayList<>();
for (Scan scan : scans) {
String badge = scan.badgeId();
if (seen.contains(badge) && !repeats.contains(badge)) {
repeats.add(badge);
}
seen.add(badge);
}
repeats.sort(null);
return repeats;
}
// The fix: count every badge once with a HashMap.
static List<String> repeatBadgesFast(List<Scan> scans) {
Map<String, Integer> counts = new HashMap<>();
for (Scan scan : scans) {
counts.merge(scan.badgeId(), 1, Integer::sum);
}
List<String> repeats = new ArrayList<>();
for (var entry : counts.entrySet()) {
if (entry.getValue() >= 2) repeats.add(entry.getKey());
}
repeats.sort(null);
return repeats;
}
public static void main(String[] args) {
List<Scan> scans = generateScans(6_000);
System.out.println("== 1. Time the slow version first ==");
long slowStart = System.nanoTime();
List<String> slowResult = repeatBadgesSlow(scans);
long slowMs = (System.nanoTime() - slowStart) / 1_000_000;
System.out.println("Scans: " + scans.size());
System.out.println("Repeat badges: " + slowResult.size());
System.out.println("repeatBadgesSlow: " + slowMs + " ms (varies by machine and run)");
System.out.println();
System.out.println("== 2. Fix it, then check the answer is identical ==");
List<String> fastResult = repeatBadgesFast(scans);
System.out.println("Same result: " + slowResult.equals(fastResult));
System.out.println();
System.out.println("== 3. Before and after, with warm-up ==");
int warmup = 20;
for (int i = 0; i < warmup; i++) {
repeatBadgesSlow(scans);
repeatBadgesFast(scans);
}
int timed = 20;
long beforeStart = System.nanoTime();
for (int i = 0; i < timed; i++) repeatBadgesSlow(scans);
long beforeNanos = System.nanoTime() - beforeStart;
long afterStart = System.nanoTime();
for (int i = 0; i < timed; i++) repeatBadgesFast(scans);
long afterNanos = System.nanoTime() - afterStart;
System.out.printf("Before (list scan): %,d ms total (%d repeats)%n", beforeNanos / 1_000_000, timed);
System.out.printf("After (HashMap): %,d ms total%n", afterNanos / 1_000_000);
System.out.println("at least 10x faster: " + (beforeNanos > afterNanos * 10) + " (ratio varies by machine and run)");
}
}
solutions/ex08.java
// Exercise 8 (capstone): a monthly utility billing report with TWO slow
// methods hiding in it -- a string-concatenation report line, and an O(n^2)
// duplicate-bill finder. Measure each separately before fixing anything.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
class Ex08 {
record Bill(String customerId, String city, double amount) {}
static final String[] CITIES = {"Pune", "Nagpur", "Nashik", "Thane"};
static List<Bill> generateBills(int count) {
Random rng = new Random(19);
int customerPoolSize = count / 5;
List<Bill> bills = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
String customer = "CUST-" + rng.nextInt(customerPoolSize);
String city = CITIES[rng.nextInt(CITIES.length)];
double amount = 150 + rng.nextInt(2850);
bills.add(new Bill(customer, city, amount));
}
return bills;
}
// Bug 1: O(n^2) -- scans two growing lists for every bill.
static List<String> duplicateBillsSlow(List<Bill> bills) {
List<String> seen = new ArrayList<>();
List<String> duplicates = new ArrayList<>();
for (Bill bill : bills) {
String customer = bill.customerId();
if (seen.contains(customer) && !duplicates.contains(customer)) {
duplicates.add(customer);
}
seen.add(customer);
}
duplicates.sort(null);
return duplicates;
}
// Fix 1: one HashMap pass.
static List<String> duplicateBillsFast(List<Bill> bills) {
Map<String, Integer> counts = new HashMap<>();
for (Bill bill : bills) {
counts.merge(bill.customerId(), 1, Integer::sum);
}
List<String> duplicates = new ArrayList<>();
for (var entry : counts.entrySet()) {
if (entry.getValue() >= 2) duplicates.add(entry.getKey());
}
duplicates.sort(null);
return duplicates;
}
// Bug 2: String += in a loop -- a brand-new String allocated on every line.
static String summaryLinesSlow(List<Bill> bills) {
String report = "";
for (Bill bill : bills) {
report += bill.customerId() + "," + bill.city() + "," + bill.amount() + "\n";
}
return report;
}
// Fix 2: StringBuilder, one mutable buffer.
static String summaryLinesFast(List<Bill> bills) {
StringBuilder report = new StringBuilder();
for (Bill bill : bills) {
report.append(bill.customerId()).append(",").append(bill.city()).append(",").append(bill.amount()).append("\n");
}
return report.toString();
}
static long timeMs(Runnable task) {
long start = System.nanoTime();
task.run();
return (System.nanoTime() - start) / 1_000_000;
}
public static void main(String[] args) {
List<Bill> bills = generateBills(5_000);
System.out.println("== 1. Time each candidate method separately ==");
long dupMs = timeMs(() -> duplicateBillsSlow(bills));
long summaryMs = timeMs(() -> summaryLinesSlow(bills));
System.out.println("Bills: " + bills.size());
System.out.println("duplicateBillsSlow: " + dupMs + " ms (varies by machine and run)");
System.out.println("summaryLinesSlow: " + summaryMs + " ms (varies by machine and run)");
System.out.println("both methods are worth fixing: " + (dupMs > 0 || summaryMs > 0));
System.out.println();
System.out.println("== 2. Fix both, then check both answers are identical ==");
List<String> slowDup = duplicateBillsSlow(bills);
List<String> fastDup = duplicateBillsFast(bills);
String slowSummary = summaryLinesSlow(bills);
String fastSummary = summaryLinesFast(bills);
System.out.println("duplicates match: " + slowDup.equals(fastDup));
System.out.println("summaries match: " + slowSummary.equals(fastSummary));
System.out.println();
System.out.println("== 3. Before and after, with warm-up ==");
int warmup = 10;
for (int i = 0; i < warmup; i++) {
duplicateBillsSlow(bills);
duplicateBillsFast(bills);
summaryLinesSlow(bills);
summaryLinesFast(bills);
}
int timed = 10;
long dupBeforeStart = System.nanoTime();
for (int i = 0; i < timed; i++) duplicateBillsSlow(bills);
long dupBeforeNanos = System.nanoTime() - dupBeforeStart;
long dupAfterStart = System.nanoTime();
for (int i = 0; i < timed; i++) duplicateBillsFast(bills);
long dupAfterNanos = System.nanoTime() - dupAfterStart;
long sumBeforeStart = System.nanoTime();
for (int i = 0; i < timed; i++) summaryLinesSlow(bills);
long sumBeforeNanos = System.nanoTime() - sumBeforeStart;
long sumAfterStart = System.nanoTime();
for (int i = 0; i < timed; i++) summaryLinesFast(bills);
long sumAfterNanos = System.nanoTime() - sumAfterStart;
System.out.printf("duplicateBills before/after: %,d ms / %,d ms total (%d repeats)%n",
dupBeforeNanos / 1_000_000, dupAfterNanos / 1_000_000, timed);
System.out.printf("summaryLines before/after: %,d ms / %,d ms total%n",
sumBeforeNanos / 1_000_000, sumAfterNanos / 1_000_000);
System.out.println("duplicateBills at least 5x faster: " + (dupBeforeNanos > dupAfterNanos * 5) + " (varies)");
System.out.println("summaryLines at least 5x faster: " + (sumBeforeNanos > sumAfterNanos * 5) + " (varies)");
}
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Assuming deep recursion fails with OutOfMemoryError |
Recursion exhausts the stack (frames), a separate pool from the heap | Expect StackOverflowError; fix with a base case or an iterative rewrite |
Comparing Strings (or any boxed type) with == |
Works by accident for pooled literals and small cached numbers, breaks for runtime-built values | .equals(), always, for value comparison |
Assuming Integer a = 127; Integer b = 127; a == b generalizes to bigger numbers |
The small-integer cache is an implementation detail with an arbitrary cutoff (default -128..127) |
.equals() for boxed numbers; never rely on cache-driven == |
Using List<Integer> (or any boxed collection) in a hot numeric loop without measuring |
Every value costs an allocation and a later collection that a primitive array never would | A primitive array (int[]), or IntStream, when the loop is actually hot |
| Trusting a single timed run | The JIT may not have warmed up yet; one run is noisy | Warm up first, time many repeats, compare totals |
| Guessing which method is slow instead of timing each one | You often fix the wrong method, or "fix" one that was never the problem | Time methods separately (or use a profiler) before changing anything |
Relying on System.gc() actually running |
It's a request the JVM is free to ignore | Never make program correctness depend on a GC happening at a specific moment |
Reading javap/bytecode output as something to hand-optimize |
Bytecode and JIT behavior change between JDK versions and are not part of the language contract | Use it to understand what the compiler already did, not as a target to write code against |
Quick recap
- The stack holds one frame per method call per thread and overflows via deep recursion; the heap holds every object, shared across all threads, and fills via too many live objects.
- Garbage collection frees heap objects nothing can reach any more; a
WeakReference(andWeakHashMap) lets you hold an object without that hold, alone, keeping it alive. ==compares identity,.equals()compares value; theStringpool means two identical literals share one object, butnew String(...)and runtime-built strings deliberately don't.- Autoboxing allocates a real object per value; a primitive loop can be an order of magnitude faster, and the small-integer cache's
==behavior is a trap, not a guarantee. javap -cshows the bytecode a method compiled to; the JIT compiles hot methods to machine code mid-run, which is most of why long-running JVM code is fast.- A fair benchmark warms up first, then times many repeats and compares totals — never trust one run.
jcmdandjstatinspect a running JVM from the outside, by process ID, with no code changes needed.- Measure before you fix: time each candidate method separately (or profile), fix only the one the numbers point at, then measure again to prove it actually helped.
Checklist
- I can say, for a
StackOverflowErrorvs. anOutOfMemoryError, which memory area ran out. - I triggered a real GC pause with
-Xlog:gcand read what the log line means. - I dropped the only strong reference to an object and watched a
WeakReferenceto it gonull. - I can explain why
new String("x") == "x"isfalsebut"x" == "x"istrue. - I measured the real cost of autoboxing in a loop, and can explain the
Integercache's==trap. - I read a method's bytecode with
javap -c, and compared default vs.-Xinttimings to see the JIT's effect. - I ran
jcmdandjstatagainst a live JVM process from a second terminal. - I found the genuinely slow method in a sample program by timing, not guessing, fixed only that one, and proved both correctness and the speed-up.