Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 36 ยท Projects and Tasks

Task Dependencies and Ordering: dependsOn, mustRunAfter, finalizedBy

Control which Gradle tasks run and in what order with dependsOn, mustRunAfter, shouldRunAfter and finalizedBy, and learn how cycles are detected.

Gradle decides what to run by building a graph from the relationships you declare between tasks. There are four relationships, and they mean different things: some say "this task needs that one", others only say "if both run, keep this order", and one says "always follow with cleanup". Choosing the right one keeps builds correct and fast. This lesson explains each with a small example, plus how Gradle rejects cycles.

The Gradle snippets are read-only. The stand-ins implement the graph logic in Java so you can test your understanding.

dependsOn: "I need that first"

dependsOn is a hard requirement. If task B depends on A, then running B also runs A first.

Kotlin
tasks.register("compile") { doLast { println("compile") } }
tasks.register("test")    { dependsOn("compile"); doLast { println("test") } }
tasks.register("package") { dependsOn("test");    doLast { println("package") } }

./gradlew package prints compile, test, package. You can depend on several tasks: dependsOn("a", "b"). Dependencies can also be added to existing tasks:

Kotlin
tasks.named("build") { dependsOn("generateDocs") }

A task can depend on another by reference (dependsOn(tasks.named("compile"))) or on a whole type with a provider. Prefer passing task providers or other task outputs so the dependency is inferred; see the inputs and outputs lesson.

mustRunAfter and shouldRunAfter: "if both run, keep this order"

Sometimes B does not need A, but if both are in the plan, A must come first. A typical case is clean before a build, or an integration test that should follow unit tests.

Kotlin
tasks.register("integrationTest") {
    mustRunAfter("test")
}

Running ./gradlew integrationTest alone does not run test. Running ./gradlew integrationTest test runs test first. shouldRunAfter is the soft version: Gradle follows it when it can, and ignores it if it would create a cycle or prevent parallel execution.

Relationship Pulls the other task in? Strength
dependsOn yes hard
mustRunAfter no hard ordering
shouldRunAfter no soft ordering
finalizedBy yes (the finalizer) always runs after

finalizedBy: "always clean up afterwards"

finalizedBy adds a finalizer: a task that runs after the first one, even if the first fails (unless it never started because a dependency failed). It is meant for cleanup and reporting.

Kotlin
tasks.register("startServer") { doLast { println("server up") } }
tasks.register("stopServer")  { doLast { println("server down") } }

tasks.register("e2eTest") {
    dependsOn("startServer")
    finalizedBy("stopServer")
    doLast { println("running e2e tests") }
}

./gradlew e2eTest prints server up, running e2e tests, server down. If the test throws, stopServer still runs. Test tasks often use this to produce a coverage report: tasks.test { finalizedBy(tasks.jacocoTestReport) }.

The ordering picture

flowchart LR
  A["startServer"] -->|"dependsOn"| B["e2eTest"]
  B -.->|"finalizedBy"| C["stopServer"]
  D["test"] -. "mustRunAfter" .-> B

Solid arrow: required. Dotted arrows: ordering and finalizers.

Cycles

If A depends on B and B depends on A, there is no valid order. Gradle detects this during graph building and fails with a message like:

TEXT
Circular dependency between the following tasks:
:a
\--- :b
     \--- :a (*)

Remove one of the edges, usually by using ordering (mustRunAfter) instead of a hard dependency.

Stand-in: ordering a graph and detecting cycles

This is not Gradle's algorithm in detail, but it is the same idea: a depth-first topological sort that reports a cycle.

Java Stand-in: topological order with cycle detection

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.

Stand-in: finalizers always run

The second stand-in shows the finalizer guarantee: cleanup happens even when the main task fails.

Java Stand-in: finalizedBy runs even after a failure

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.

Choosing the right relationship

  • The second task uses the output of the first: dependsOn, or better, wire the output (see inputs and outputs).
  • The two tasks are independent but you want a stable order in a combined run: mustRunAfter.
  • You would like an order but it is optional: shouldRunAfter.
  • Something must always be cleaned up or reported after a task: finalizedBy.
  • Never add a dependsOn just to force an order; it makes ./gradlew integrationTest run unrelated work.

You can inspect the plan with ./gradlew <task> --dry-run, and print the graph in a build scan.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Task B has mustRunAfter("A"). You run ./gradlew B. What happens?

    mustRunAfter only orders tasks that are both in the plan. It does not add A.
  2. 2. What is finalizedBy typically used for?

    A finalizer runs after the finalized task, whether it succeeds or fails.
  3. 3. Task a dependsOn b and b dependsOn a. What does Gradle do?

    A cycle has no valid order, so Gradle refuses to run the build.
  4. 4. Which relationship is a soft ordering that Gradle may ignore to avoid a cycle?

    shouldRunAfter is a hint; Gradle drops it if honoring it would create a cycle.

Summary

  • dependsOn pulls a task in and runs it first.
  • mustRunAfter and shouldRunAfter only order tasks that are already in the plan (hard vs soft).
  • finalizedBy adds a finalizer that runs after the task, even on failure.
  • Cycles are detected while the graph is built; break them with ordering instead of dependencies.
  • Use --dry-run to preview the order.

Next: Inputs, Outputs and Up-to-date Checks