Sub topic 1
Start with a measurable goal
Profiling without a goal produces data but no decisions. This chapter shows how to turn "the app feels slow" into numbers you can measure, compare and agree on. Every later chapter in this tutorial assumes you have done this first.
Prerequisites
This chapter assumes you can:
- Write and run basic Java programs from the command line.
- Read a stack trace.
- Explain what a thread and the heap are at a basic level.
You do not need any profiling tools yet. Later chapters introduce them.
Why a vague goal fails
"Make it faster" cannot be tested. You cannot tell when you are done, and you cannot tell whether a change helped or only moved the cost somewhere else. A change that cuts CPU time by 30% may raise memory use, and without a stated goal you will not notice the trade.
A useful goal has four parts:
- A metric (what you measure).
- A target value (what counts as good enough).
- A workload (what the application is doing while you measure).
- An environment (hardware, JVM version, flags, data size).
For example: "Under 200 concurrent users on the staging cluster, the 99th percentile latency of POST /orders stays below 250 ms." All four parts are present, and anyone can check it.
The main metrics
Most Java performance goals fall into three groups: latency, throughput and footprint.
| Metric | What it measures | Typical goal wording |
|---|---|---|
| Latency | Time to complete one operation | p99 under 250 ms |
| Throughput | Operations completed per unit of time | At least 2,000 requests per second |
| Memory footprint | Heap and total process memory | Heap use under 2 GB at steady state |
| CPU utilization | Share of CPU cores used | Under 60% at peak load |
| Startup time | Time until the app serves its first request | Ready within 20 seconds |
Latency and throughput are related but different. A system can process many requests per second (high throughput) while some individual requests wait a long time (bad latency). Garbage collection pauses are a common cause of this pattern: most requests are fast, and a few are caught in a pause.
Percentiles, not averages
A percentile tells you the value below which a given share of measurements fall. The p50 (median) latency is the value that half of requests beat. The p99 latency is the value that 99% of requests beat, so 1 request in 100 is slower.
Averages hide the slow tail. Suppose 99 requests take 10 ms and one takes 2,000 ms. The average is about 30 ms, which looks fine. The p99 is near the slow request, and that is what the unlucky user experiences.
You can compute percentiles from a list of samples with a few lines of Java:
import java.util.Arrays;
public class Percentiles {
static long percentile(long[] sortedMillis, double p) {
int index = (int) Math.ceil(p / 100.0 * sortedMillis.length) - 1;
return sortedMillis[Math.max(0, index)];
}
public static void main(String[] args) {
long[] samples = new long[100];
Arrays.fill(samples, 10);
samples[99] = 2000;
Arrays.sort(samples);
long sum = 0;
for (long s : samples) {
sum += s;
}
System.out.println("average = " + sum / samples.length + " ms");
System.out.println("p50 = " + percentile(samples, 50) + " ms");
System.out.println("p99 = " + percentile(samples, 99) + " ms");
System.out.println("max = " + percentile(samples, 100) + " ms");
}
}This prints an average of 29 ms, a p50 of 10 ms, a p99 of 10 ms and a max of 2000 ms. With only 100 samples, the p99 lands on the 99th value, so the single outlier shows up only in the max. Percentiles need enough samples to be meaningful: for a trustworthy p99 you want thousands of samples, and for p99.9 you want tens of thousands.
Choosing targets
A target should come from a real requirement, not from a guess.
- User experience. If a page must feel instant, a budget of a few hundred milliseconds end to end is common. Work backward to split that budget across services.
- Service agreements. If a contract says 99% of calls finish within 500 ms, that is your p99 target, and you should aim for a margin below it.
- Capacity. If you must handle a known peak load on a fixed number of machines, throughput per machine is the target.
- Cost. If you want to run on smaller instances, memory and CPU limits are the target.
Write down the current value first. This is the baseline. A target of "p99 under 250 ms" is only useful if you know the app is at 800 ms now, or at 240 ms. In the second case, you may not need to optimize at all.
Measure under a realistic workload
A measurement is only as good as the workload behind it. Common mistakes:
- Tiny data. A query that is fast on 100 rows may be slow on 10 million.
- Cold start only. The JVM compiles hot code while running, so the first seconds are slower than steady state. Later chapters cover this as JIT warmup. For now, discard or separate the early measurements.
- Unrepresentative traffic. If production has 80% reads and your test sends only writes, the results will mislead.
- Noisy machines. Other processes, laptop power saving and shared cloud hosts add variation. Run the test several times and look at the spread.
- Different configuration. Different heap size, garbage collector or JVM version changes results.
Seeing a baseline in practice
A quick way to start is a program with a clear, repeatable workload. This one concatenates strings in a loop and will serve as a running example in later chapters:
public class Slow {
public static void main(String[] args) {
long start = System.nanoTime();
for (int round = 0; round < 200; round++) {
String s = "";
for (int i = 0; i < 5_000; i++) {
s += i;
}
if (s.length() == 0) {
System.out.println("unreachable");
}
}
System.out.println((System.nanoTime() - start) / 1_000_000 + " ms");
}
}Run it several times and record each result:
javac Slow.java
for i in 1 2 3 4 5; do java Slow; doneThe numbers will differ from run to run. Write down the range, not a single value. A goal such as "finish in under half the current time" is then something you can check. The if at the end uses the result so the compiler cannot treat the loop as useless work.
How the pieces fit together
The workflow for the whole tutorial begins with the goal, and every later step feeds back into it.
The first decision point matters. If the baseline already meets the goal, the correct action is to stop.
Common errors
- Optimizing before measuring. Intuition about hot spots is often wrong. Measure first.
- Optimizing the wrong metric. Lowering average latency while p99 stays flat does not help users who hit the slow tail.
- Changing several things at once. You cannot tell which change helped, or which one hurt.
- Treating one run as truth. Single runs vary. Repeat them and compare ranges.
- Ignoring the cost side. A speedup that doubles memory use may break the footprint goal.
- Having no stop condition. Without a target, you can tune forever.
Recording your goal
Keep a short written record next to the code. A plain text file is enough:
Goal: p99 latency of POST /orders under 250 ms
Workload: 200 concurrent users, 70% reads, 10 minutes after 2 minute warmup
Environment: staging, 4 vCPU, 8 GB RAM, JDK 17, -Xmx4g
Baseline: p50 80 ms, p99 610 ms, 5 runs, p99 range 580 to 640 ms
Date: 2026-11-26When you change something later, add the new numbers under the same workload. This record is what lets you prove that a fix worked.
Exercise
A service reports an average latency of 40 ms, and the team says performance is fine. Users still complain about occasional long waits. What should you measure, and why is the average misleading?
Show answer
Measure latency percentiles such as p95, p99 and p99.9, and the maximum, over enough samples to make them stable. The average blends many fast requests with a few very slow ones, so a small slow tail barely moves it. Users who hit that tail see long waits even though the average looks healthy. Write a goal such as "p99 under 250 ms at 200 concurrent users" and compare against a recorded baseline.
Exercise
Name the four parts of a testable performance goal, and give one example of a goal that is missing the workload part.
Show answer
The four parts are a metric, a target value, a workload and an environment. "p99 latency under 250 ms" has a metric and a target but no workload, so it does not say how many users or what kind of requests are involved, and two people could measure it under different conditions and disagree.