DEV Community

Said Olano
Said Olano

Posted on

Load Testing Java Applications with Apache JMeter: A Practical Guide

Performance problems rarely show up in unit tests. They show up on a Friday afternoon, when a checkout endpoint that responded in 120 ms at lunch starts taking eight seconds under real traffic. Apache JMeter is one of the most widely used open-source tools for catching those problems before users do. It is mature, scriptable, and it speaks HTTP, JDBC, JMS, and more out of the box. For Java teams, it also fits naturally into the build pipeline, because it runs on the JVM and can be driven from Maven, Gradle, Jenkins, or GitHub Actions.

This guide walks through a practical workflow: building a test plan, running it headless, adding assertions and correlation, writing a custom Java sampler, driving JMeter from Java code, reading the results, and wiring everything into CI. The examples target a Spring Boot service, but the ideas apply to any HTTP API.

What JMeter Actually Does

JMeter simulates many users sending requests to a system under test. Each simulated user runs through a sequence of steps, and JMeter records how long each request takes, whether it succeeded, and how many bytes came back. You then analyze those numbers to find bottlenecks, capacity limits, and regressions.

A test plan is a tree of elements. The most important ones are:

  • Thread Group: defines how many virtual users run, how fast they ramp up, and how long they keep going.
  • Samplers: send the actual requests. The HTTP Request sampler is the one you will use most.
  • Config Elements: set shared values such as base URL, headers, and cookies. HTTP Request Defaults and HTTP Header Manager are the usual choices.
  • Timers: add think time between requests so virtual users behave more like real people. Without timers you measure a flood, not a user journey.
  • Assertions: check that a response is correct. A fast 500 error is not a passing test.
  • Extractors: pull values out of one response, such as a token or an ID, and reuse them in the next request. This is called correlation.
  • Listeners: display or store results. Use them sparingly during real load runs, because they consume resources.

A minimal plan for a Spring Boot REST endpoint looks like this in JMeter's tree view:

Test Plan
 ├── Thread Group (50 users, 60s ramp-up, 5 min duration)
 │    ├── HTTP Request Defaults (host: orders.internal, port: 8080)
 │    ├── HTTP Header Manager (Content-Type: application/json)
 │    ├── HTTP Request: POST /api/orders
 │    │    ├── Response Assertion (status 201)
 │    │    └── JSON Extractor (orderId = $.id)
 │    ├── Constant Timer (500 ms)
 │    └── HTTP Request: GET /api/orders/${orderId}
 │         └── Response Assertion (status 200)
 └── Summary Report (listener, used only in GUI mode)
Enter fullscreen mode Exit fullscreen mode

Notice the JSON Extractor. The second request uses the order ID created by the first one. That is the kind of dependency that real users create, and it is the part most teams skip the first time.

Never Run Load Tests in GUI Mode

The JMeter GUI is for building and debugging plans. It is not for load generation. Listeners that render graphs, and the GUI itself, consume memory and CPU on the machine running the test. If the load generator is the bottleneck, your results describe the load generator, not your application.

Save the plan as a .jmx file and run it headless:

jmeter -n \
  -t plans/orders-load.jmx \
  -l results/orders-run-01.jtl \
  -e -o reports/orders-run-01 \
  -Jhost=orders.staging.internal -Jthreads=50 -Jduration=300
Enter fullscreen mode Exit fullscreen mode

The flags matter. -n runs without the GUI, -t names the test plan, -l writes raw results, and -e -o generates the HTML dashboard into a folder once the run finishes. The -J properties let you parameterize the plan. In the plan, reference them with ${__P(threads,10)}, where the second argument is a default.

Correlation and Dynamic Data

Most real applications return data that changes on every call: tokens, session cookies, generated IDs, CSRF values. If you hardcode one, the server rejects the request and your test measures error responses. Use extractors:

  • JSON Extractor for JSON bodies, using JSONPath expressions such as $.id or $.data[0].token.
  • Regular Expression Extractor for HTML pages or plain text.
  • CSV Data Set Config to feed realistic inputs, such as thousands of different customer IDs, from a file instead of reusing one value for every user.

Also remember that real clients send a login before doing anything else. A plan that skips authentication is testing a path that real users do not take.

Writing a Custom Java Sampler

Sometimes an HTTP request is not enough. You may need to call a gRPC service, publish to a queue through a proprietary client, or run a domain-specific calculation that must be measured. JMeter supports this through the Java Request sampler, which runs a class implementing JavaSamplerClient.

import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.config.Arguments;

public class PricingEngineSampler extends AbstractJavaSamplerClient {

    private PricingClient client;

    @Override
    public Arguments getDefaultParameters() {
        Arguments args = new Arguments();
        args.addArgument("endpoint", "http://pricing.internal:9000");
        args.addArgument("sku", "SKU-1001");
        return args;
    }

    @Override
    public void setupTest(JavaSamplerContext context) {
        // Called once per thread before the iterations start
        client = new PricingClient(context.getParameter("endpoint"));
    }

    @Override
    public SampleResult runTest(JavaSamplerContext context) {
        SampleResult result = new SampleResult();
        result.sampleStart();
        try {
            String sku = context.getParameter("sku");
            var price = client.quote(sku);
            result.setSuccessful(price != null && price.amount().signum() > 0);
            result.setResponseData(price.toString(), "UTF-8");
            result.setResponseCode("200");
        } catch (Exception e) {
            result.setSuccessful(false);
            result.setResponseCode("500");
            result.setResponseMessage(e.getMessage());
        } finally {
            result.sampleEnd();
        }
        return result;
    }

    @Override
    public void teardownTest(JavaSamplerContext context) {
        client.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

Two details to get right. Call sampleStart() and sampleEnd() yourself, so the timing covers only the operation you care about. And create expensive clients in setupTest, not in runTest, so you measure the service rather than your client's construction cost.

Driving JMeter from Java Code

Keeping test plans as XML in a repository is fine, but many Java teams prefer tests written in code, reviewed in pull requests, and refactored with the rest of the codebase. The jmeter-java-dsl library from Abstracta lets you build a plan with a fluent Java API and run it from a JUnit test.

import static us.abstracta.jmeter.javadsl.JmeterDsl.*;

import java.time.Duration;
import org.junit.jupiter.api.Test;
import us.abstracta.jmeter.javadsl.core.TestPlanStats;

class OrdersLoadTest {

    @Test
    void ordersEndpointStaysUnderLatencyBudget() throws Exception {
        TestPlanStats stats = testPlan(
            threadGroup(50, 100,
                httpSampler("http://orders.staging.internal:8080/api/orders/42")
                    .method("GET")
                    .assertion(responseCode().is(200))
            ),
            jtlWriter("build/results/orders.jtl"),
            htmlReporter("build/reports/orders")
        ).run();

        // Fail the build if the 95th percentile exceeds 400 ms
        assertThat(stats.overall().sampleTimePercentile95()
            .toMillis()).isLessThan(400);
    }
}
Enter fullscreen mode Exit fullscreen mode

Check the DSL version you use against its documentation, since method names evolve between releases. The principle stays the same: the test is code, it runs under JUnit, and a regression fails the build like any other test.

For teams that already use Maven, the jmeter-maven-plugin offers a similar path: it runs .jmx files during a build phase and can fail the build when thresholds are crossed. Pick one approach per project to keep things consistent.

Reading the Results

A load test produces a lot of numbers. Four of them matter most:

  • Throughput: requests per second the system actually handled. If throughput flattens while you add users, you have found a saturation point.
  • Response time percentiles: the average hides the problem. Track p90, p95, and p99. A healthy average with a terrible p99 means some users have a bad experience.
  • Error rate: any non-zero error rate under normal load deserves investigation. Look at the response codes first. A wave of 503s points to a different problem than a wave of timeouts.
  • Latency over time: a graph that slowly climbs during a 30-minute soak test usually means a memory leak, a connection pool that never drains, or a cache that never evicts.

Correlate JMeter's view with the server's view. In a Spring Boot service, expose Actuator metrics to Prometheus and watch JVM heap, GC pause time, thread pool saturation, and HikariCP connection wait time while the test runs. JMeter tells you that something is slow. The JVM and database metrics tell you why.

Running JMeter in CI

A load test that only runs on someone's laptop will be forgotten. Put it in the pipeline, but scope it carefully. Full-scale load tests belong in a dedicated environment on a schedule, while a smaller smoke-level test can run on every merge.

A GitHub Actions job that runs a headless plan and publishes the report might look like this:

name: orders-performance
on:
  schedule:
    - cron: "0 2 * * *"
  workflow_dispatch:

jobs:
  load-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: "21"
      - name: Install JMeter
        run: |
          wget -q https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-5.6.3.tgz
          tar -xzf apache-jmeter-5.6.3.tgz
          echo "$PWD/apache-jmeter-5.6.3/bin" >> "$GITHUB_PATH"
      - name: Run plan
        run: |
          jmeter -n -t plans/orders-load.jmx \
            -l results.jtl -e -o report \
            -Jhost=${{ secrets.STAGING_HOST }} -Jthreads=50 -Jduration=300
      - name: Fail on errors
        run: |
          errors=$(awk -F, 'NR>1 && $8=="false"' results.jtl | wc -l)
          if [ "$errors" -gt 0 ]; then echo "Found $errors failed samples"; exit 1; fi
      - uses: actions/upload-artifact@v4
        with:
          name: jmeter-report
          path: report
Enter fullscreen mode Exit fullscreen mode

Check the JMeter version on the Apache archive before you copy this, since older releases disappear from the mirror. The awk step reads the success column of the default CSV output, which is the eighth field, and fails the job if any sample did not pass.

Best Practices

  • Model real journeys, not isolated endpoints. Users log in, browse, add to cart, and pay. Test the sequence.
  • Add think time. A constant or Gaussian random timer between steps produces realistic concurrency.
  • Warm up before measuring. JVM services compile hot code paths during the first minutes. Discard the warm-up period from your results.
  • Use realistic data volumes. A test against an empty database tells you nothing about a table with fifty million rows.
  • Separate the load generator from the target. Run JMeter on its own machine, and watch its CPU. A saturated generator produces fake latency.
  • Set explicit thresholds. "The system should feel fast" is not a requirement. "p95 under 400 ms at 200 requests per second" is one you can test.
  • Keep test data and secrets out of the plan. Read credentials from properties or a vault, never from the .jmx file committed to Git.
  • Version the plans. Treat .jmx files like source code, and review changes to them.

A Practical Roadmap

If your team is starting from zero, a sensible sequence is:

  1. Record or script one critical user journey with the HTTP(S) Test Script Recorder or by hand.
  2. Add assertions, correlation, and realistic think times until the plan passes against a staging environment with one user.
  3. Run a headless baseline at moderate load and save the report as a reference.
  4. Add a nightly job in CI that compares the new run against the baseline and fails on a threshold breach.
  5. Expand to soak tests and stress tests, and connect the results to your application metrics dashboards.

Performance testing is not a one-time event. It is a habit that catches regressions early, when they are cheap to fix.

Key Takeaways

JMeter is a capable, free tool that fits well into Java delivery pipelines. Run it headless, correlate dynamic data, model real user journeys, and read percentiles instead of averages. Write custom samplers when HTTP is not enough, and consider a Java DSL when you want tests to live beside the code they measure. Above all, put a performance check in the pipeline so that slow code is caught by a build, not by a customer.

Top comments (0)