Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 41 ยท Releasing and Production

Maven in CI and Faster Builds

Run Maven on GitHub Actions, cache the local repository, build modules in parallel with -T, use mvnd and the build cache extension, and model build times.

A Maven build that takes ten minutes on a laptop will take ten minutes on every pull request, every push and every release. Multiply by a team and the cost is large, in money and in waiting. Continuous integration (CI) is where build speed matters most, and Maven gives you several levers: cache what you download, build independent modules in parallel, avoid repeating work, and keep the process warm.

This lesson shows a complete GitHub Actions workflow, then each speed-up in turn. CI servers and Maven itself cannot run on this site, so workflow files and commands are read-only. The two Java stand-ins model the arithmetic: how parallel threads shorten a multi-module build, and how a cache key decides between a hit and a miss.

Where the time goes

Downloads Dependencies and plugins from the network.
Compiling Every module, every time.
Tests Usually the biggest share.
JVM startup Maven itself starts cold.
1 / 2

A GitHub Actions workflow

A workflow is a YAML file in .github/workflows/. This one checks out the code, installs a JDK, caches the local repository and runs the full verification on each push and pull request:

YAML
name: build
on:
  push:
    branches: [main]
  pull_request:

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: "25"
          cache: maven
      - name: Build and test
        run: ./mvnw -B -ntp verify
      - name: Upload test reports
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: surefire-reports
          path: "**/target/surefire-reports"

Several details matter. ./mvnw runs the Maven wrapper, so CI uses exactly the Maven version the project pins. -B (batch mode) switches off interactive prompts and colors. -ntp hides the noisy "downloading" lines (see the command line toolbox). Use verify, not package, so integration tests and quality checks run too. The cache: maven option of setup-java saves ~/.m2/repository between runs, keyed on a hash of your POM files.

The full pipeline, with coverage and a tagged release job, is built step by step in the CI pipeline project.

Caching the local repository

Without a cache, every CI run starts with an empty ~/.m2 and re-downloads hundreds of megabytes. A cache restores it first and saves it after. The key idea is the cache key: it is built from something that changes exactly when the dependencies change, typically the hash of all pom.xml files. If the key matches a stored cache, the job is a hit and downloads little; if you edit a POM, the key changes and the job starts from the nearest older cache (a restore key) or from scratch.

YAML
- uses: actions/cache@v4
  with:
    path: ~/.m2/repository
    key: maven-${{ hashFiles('**/pom.xml') }}
    restore-keys: |
      maven-

Two cautions: never cache artifacts built from your own project into the shared repository without cleaning them (a stale -SNAPSHOT of your own module can hide a failing build), and give pull requests from forks only read access to the cache, a rule GitHub enforces for security.

Parallel builds with -T

In a multi-module build, modules that do not depend on each other can compile at the same time. The -T option sets the thread count:

Terminal
mvn -T 4 verify          # four threads
mvn -T 1C verify         # one thread per CPU core
mvn -T 0.5C verify       # half as many threads as cores

Parallelism is limited by the dependency graph: a module cannot start until the modules it depends on are finished, so the critical path sets the minimum time however many threads you have. Plugins also have to be thread-safe. Maven prints a warning for plugins that do not declare it; a plugin that writes to a shared file is a typical culprit. Test parallelism inside Surefire is a separate setting (parallel and forkCount), described in running tests with Surefire.

Doing less work

The fastest build step is the one you skip:

  • Build only the affected modules. -pl selects modules and -am adds the modules they need. A pull request that touches service can run mvn -pl service -am verify. A script can derive the list from git diff.
  • Resume after a failure. -rf :module restarts the reactor from a module (see multi-module builds).
  • Skip what you have already proven. Run unit tests on every push, slower integration tests nightly or on the main branch. Keep checks in the pipeline, though; -DskipTests on a release job is an accident waiting to happen.
  • Avoid clean by default. Maven's incremental compilation detects changes; clean throws that away. On CI the workspace is fresh anyway.

The Maven daemon and the build cache

mvnd, the Maven daemon, keeps one JVM running between builds and reuses plugin classloaders, so repeated commands start almost instantly and run warm code. It also parallelises by default. It is most useful on developer machines and long-lived CI agents:

Terminal
mvnd verify
mvnd -T 1C clean verify

The Maven Build Cache Extension goes further: it records a fingerprint of a module's inputs (sources, POM, dependencies) and stores its outputs. If the fingerprint matches a stored one, the module's phases are replaced by a cache restore. Installed through .mvn/extensions.xml, it can turn a no-change rebuild of a big project into seconds, and a remote cache lets CI and laptops share results. It requires careful configuration of what counts as an input, so adopt it after the simpler levers.

XML
<extensions>
  <extension>
    <groupId>org.apache.maven.extensions</groupId>
    <artifactId>maven-build-cache-extension</artifactId>
    <version>1.2.0</version>
  </extension>
</extensions>

Check the project documentation for the current version number before using it.

From CI to container images

Once the build passes, the artifact often ends up in a container. Compile inside a Maven image, then copy only the jar into a slim runtime image, as shown in multi-stage builds and the Java recipe. To keep that fast, copy the POM first and run mvn dependency:go-offline in its own layer, so Docker reuses the downloaded dependencies until the POM changes.

A parallel build model

This stand-in simulates the reactor. Each module has a build time in seconds and dependencies. The scheduler runs up to N modules at once; a module starts when all its dependencies are done. Try different thread counts and see how the total time stops improving at the critical path.

Java Reactor timing with -T

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With one thread the build takes the sum of all module times (120 seconds). Extra threads help until the critical path (core, persistence, admin, app) is the limit. A faster compile on the longest chain beats adding more cores, which is why splitting a giant module can speed up the whole reactor.

A cache key model

The second stand-in imitates hashFiles('**/pom.xml') and a store of caches. It reports a hit, a partial restore through the prefix, or a miss, and adds a rough time for downloading.

Java Cache hit, partial restore or miss

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A partial restore is still a big win because most of the dependency tree is unchanged; only the new artifacts download. The times are invented for illustration; measure your own builds with the -B log timestamps before and after each change.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does mvn -T 1C verify do?

    -T sets the thread count; the C suffix means multiplied by the number of cores. Independent modules then build in parallel.
  2. 2. What limits how much -T can speed up a multi-module build?

    A module waits for its dependencies, so the longest dependency chain sets a minimum time regardless of threads.
  3. 3. What is a sensible cache key for ~/.m2/repository in CI?

    The key should change exactly when dependencies change. A hash of the POM files does that; a timestamp would never hit, a constant would never refresh.
  4. 4. Why does a CI workflow use ./mvnw -B -ntp verify?

    The wrapper pins Maven, -B disables prompts and -ntp removes transfer-progress noise from logs; verify runs all checks.

Summary

  • A CI workflow checks out, sets up the JDK, restores a cache and runs ./mvnw -B -ntp verify.
  • Cache ~/.m2 with a key derived from the POM files, with a prefix fallback for partial restores.
  • -T builds independent modules in parallel; the critical path is the floor.
  • Build only what changed with -pl and -am; keep verify and quality checks on the important branches.
  • mvnd keeps a warm JVM, and the build cache extension can skip unchanged modules entirely.

Next, go beyond configuring plugins and write one in Writing a Simple Maven Plugin.