TExcelTAD
Home › Java Builds: Maven & Gradle › The Task Graph

The Task Graph

A Gradle build runs in three phases:

  1. Initialization: read settings.gradle.kts, decide which projects take part.
  2. Configuration: run every participating build script. Scripts register and configure tasks; they don't do the work.
  3. Execution: compute the graph of tasks needed for the tasks you asked for, then run them in dependency order, skipping the ones that are up to date.

The graph is computed per invocation. gradle compileJava builds a small graph, gradle build a large one; there is no fixed lifecycle as in Maven, only tasks and the edges between them.

Tasks and their edges

A task is a named unit of work with actions (doFirst, doLast). Four kinds of relationship shape the graph:

Relationship Meaning
dependsOn(x) x must run (and finish) before this task; requesting this task pulls x in
finalizedBy(x) x runs after this task, even if it failed; pulled in automatically
mustRunAfter(x) if both are in the graph, run x first; doesn't pull x in
shouldRunAfter(x) like mustRunAfter, but Gradle may ignore it (parallel builds, cycles)

A build with no plugins at all shows the mechanics:

bash · try it yourself
mkdir graph && cd graph
cat > settings.gradle.kts <<'KTS'
rootProject.name = "graph"
KTS
cat > build.gradle.kts <<'KTS'
val generate = tasks.register("generate") {
    doLast { println("generate: writing sources") }
}
val compile = tasks.register("compile") {
    dependsOn(generate)
    doLast { println("compile: compiling") }
}
tasks.register("lint") {
    doLast { println("lint: checking style") }
}
tasks.register("report") {
    doLast { println("report: summary written") }
}
tasks.register("pack") {
    group = "distribution"
    description = "Packs the compiled code."
    dependsOn(compile)
    mustRunAfter("lint")
    finalizedBy("report")
    doLast { println("pack: archive created") }
}
KTS
echo '$ gradle -q pack';        gradle -q pack
echo '$ gradle -q pack lint';   gradle -q pack lint
echo '$ gradle -q pack -x compile'; gradle -q pack -x compile
echo '$ gradle pack --dry-run'; gradle pack --dry-run
$ gradle -q pack
generate: writing sources
compile: compiling
pack: archive created
report: summary written
$ gradle -q pack lint
lint: checking style
generate: writing sources
compile: compiling
pack: archive created
report: summary written
$ gradle -q pack -x compile
pack: archive created
report: summary written
$ gradle pack --dry-run
:generate SKIPPED
:compile SKIPPED
:pack SKIPPED
:report SKIPPED

BUILD SUCCESSFUL in 553ms
Consider enabling configuration cache to speed up this build: https://docs.gradle.org/9.8.2/userguide/configuration_cache_enabling.html
  • gradle pack pulled in compile and generate (dependencies) and report (finalizer). lint didn't run: mustRunAfter only orders, it never adds.
  • gradle pack lint asked for both, and the ordering rule put lint before pack, although it was named second (here even before pack's dependencies, which is equally valid).
  • -x compile removes a task (and what only it needed) from the graph.
  • --dry-run (short: -m) prints the plan with every task marked SKIPPED, without running anything. It's the quickest way to answer "what would this command do?".

The Java plugin's graph

The java plugin registers about twenty tasks wired into a graph that resembles Maven's lifecycle, but is just tasks:

bash · try it yourself
mkdir lib && cd lib
cat > settings.gradle.kts <<'KTS'
rootProject.name = "lib"
KTS
cat > build.gradle.kts <<'KTS'
plugins { java }
KTS
echo '$ gradle build -m';           gradle build -m | grep '^:'
echo '$ gradle jar -m';             gradle jar -m | grep '^:'
echo '$ gradle build -x test -m';   gradle build -x test -m | grep '^:'
gradle help --task build | grep -A1 -E '^(Description|Group)'
$ gradle build -m
:compileJava SKIPPED
:processResources SKIPPED
:classes SKIPPED
:jar SKIPPED
:assemble SKIPPED
:compileTestJava SKIPPED
:processTestResources SKIPPED
:testClasses SKIPPED
:test SKIPPED
:check SKIPPED
:build SKIPPED
$ gradle jar -m
:compileJava SKIPPED
:processResources SKIPPED
:classes SKIPPED
:jar SKIPPED
$ gradle build -x test -m
:compileJava SKIPPED
:processResources SKIPPED
:classes SKIPPED
:jar SKIPPED
:assemble SKIPPED
:check SKIPPED
:build SKIPPED
Description
     Assembles and tests this project.
--
Group
     build

build is an aggregate task: it does nothing itself and depends on assemble (produce the artifacts) and check (run verification such as test). gradle jar skips the whole test half of the graph, because nothing in jar's dependencies needs it, which is quicker than Maven's package, where the lifecycle always runs test first.

gradle tasks lists the tasks meant for people (those with a group), and gradle tasks --all everything.

A model of execution order

Under the hood Gradle runs a topological sort of the requested tasks plus everything reachable through dependsOn and finalizedBy, and treats mustRunAfter as an extra ordering edge between tasks that are already in the graph. A small model reproduces the session above (when several orders are valid, Gradle's choice depends on details such as the order of edges; the model follows the real output):

python · try it yourself
DEPENDS = {"generate": [], "compile": ["generate"], "lint": [], "report": [], "pack": ["compile"]}
FINALIZED_BY = {"pack": ["report"]}
MUST_RUN_AFTER = {"pack": ["lint"]}

def plan(requested, excluded=()):
    graph = set()
    def add(task):
        if task in graph or task in excluded:
            return
        graph.add(task)
        for d in DEPENDS[task] + FINALIZED_BY.get(task, []):
            add(d)
    for t in requested:
        add(t)
    order, done = [], set()
    def visit(task):
        if task in done:
            return
        done.add(task)
        before = [t for t in MUST_RUN_AFTER.get(task, []) if t in graph] + DEPENDS[task]
        for d in before:
            if d in graph:
                visit(d)
        order.append(task)
        for f in FINALIZED_BY.get(task, []):
            visit(f)
    for t in requested:
        if t in graph:
            visit(t)
    return order

print("pack           ->", plan(["pack"]))
print("pack lint      ->", plan(["pack", "lint"]))
print("pack -x compile->", plan(["pack"], excluded=("compile",)))
pack           -> ['generate', 'compile', 'pack', 'report']
pack lint      -> ['lint', 'generate', 'compile', 'pack', 'report']
pack -x compile-> ['pack', 'report']

Tip: Avoid dependsOn between tasks that exchange files. Wire the output of one task into the input of the other (from(generate) or a Provider), and Gradle infers the dependency for you; that's the subject of Lazy Configuration.

Test yourself

Task pack has mustRunAfter("lint"). You run gradle pack. Does lint run?

  1. Yes, before pack
  2. Yes, after pack
  3. No: mustRunAfter only orders tasks that are already in the graph
  4. Only with --dry-run

What does gradle build --dry-run do?

  1. Builds without tests
  2. Prints the tasks that would run, in order, without executing any
  3. Runs the build in a sandbox
  4. Deletes build outputs

Why can gradle jar be faster than mvn package?

  1. Gradle compiles faster
  2. jar only pulls in the tasks it depends on; Maven's lifecycle runs test before package
  3. Gradle skips compilation
  4. Maven always cleans first