Gradle Build

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 263 of 306

A Gradle build is a graph of tasks. When you type ./gradlew build, Gradle works out every task that build needs, orders them, skips the ones that are already up to date, and runs the rest.

This lesson explains the three phases of a Gradle build, how to read the task graph and task outcomes, how to write and connect your own tasks, how to configure built-in tasks, and how to split code into a multi-project build. It ends with a two-module library system that generates its own build information. If build.gradle.kts is new to you, start with Gradle in Java.


The Three Phases of a Gradle Build

Every Gradle build runs in three phases:

PhaseWhat happensFiles involved
InitializationFinds which projects take partsettings.gradle.kts
ConfigurationRuns the build scripts and creates the tasks that are neededbuild.gradle.kts
ExecutionRuns the selected tasks in dependency orderTask actions (doFirst, doLast)

Code placed directly in a build script runs during configuration. Code inside doLast runs during execution, and only if that task is selected.

// build.gradle.kts
println("Configuring project ${project.name}")

tasks.register("hello") {
    println("Configuring task hello")
    doLast {
        println("Hello from the execution phase")
    }
}
./gradlew hello
./gradlew help -q

Output:

> Configure project :
Configuring project build-demo
Configuring task hello

> Task :hello
Hello from the execution phase

BUILD SUCCESSFUL in 640ms
1 actionable task: 1 executed
Configuring project build-demo

How it works:

  • tasks.register creates the task lazily. Its configuration block only runs when the task is actually needed.
  • The second command runs help, so hello is never configured and its message does not appear. The top-level println still runs, because the whole script is evaluated in every build.
  • Put real work in doLast. Work done at configuration time slows down every Gradle command, even ./gradlew tasks.

View the Gradle Task Graph With a Dry Run

build is a lifecycle task: it does nothing itself but depends on other tasks. A dry run (-m) prints the full list of tasks Gradle would run, without running them.

./gradlew build -m

Output for an application project:

:compileJava SKIPPED
:processResources SKIPPED
:classes SKIPPED
:jar SKIPPED
:startScripts SKIPPED
:distTar SKIPPED
:distZip SKIPPED
:assemble SKIPPED
:compileTestJava SKIPPED
:processTestResources SKIPPED
:testClasses SKIPPED
:test SKIPPED
:check SKIPPED
:build SKIPPED

BUILD SUCCESSFUL in 512ms

How it works:

  • Here SKIPPED only means "not run because this is a dry run".
  • build depends on assemble (create outputs) and check (verify them). check depends on test, which depends on the compiled test classes, and so on.
  • Lifecycle tasks such as classes, assemble, check and build are convenient names for groups of real work.

Gradle Task Outcomes: UP-TO-DATE, NO-SOURCE and FROM-CACHE

With the plain console, Gradle prints the outcome of every task.

./gradlew build --console=plain

Output of a second build with no changes (shortened):

> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :jar UP-TO-DATE
> Task :compileTestJava UP-TO-DATE
> Task :test UP-TO-DATE
> Task :check UP-TO-DATE
> Task :build UP-TO-DATE

BUILD SUCCESSFUL in 798ms
OutcomeMeaning
(no label)The task ran
UP-TO-DATEInputs and outputs unchanged since the last run, so it was skipped
NO-SOURCEThe task had no input files, for example an empty src/main/resources
FROM-CACHEOutputs were copied from the build cache instead of being recomputed
SKIPPEDThe task was excluded (-x) or its onlyIf condition was false

How it works:

  • Before running a task, Gradle compares a fingerprint of its input files and settings with the previous run. If nothing changed and the outputs still exist, it skips the task.
  • Edit one Java file and compileJava runs again; jar and test run again too because their inputs (the compiled classes) changed.
  • --rerun-tasks forces every task to run, which helps when you suspect a stale result.

Create a Custom Gradle Task

Register your own task with a group, a description and an action.

tasks.register("courseInfo") {
    group = "gocourse"
    description = "Prints information about this project."

    val projectName = project.name          // read at configuration time
    val javaVersion = java.toolchain.languageVersion

    doLast {
        println("Project: $projectName")
        println("Java toolchain: ${javaVersion.get()}")
    }
}
./gradlew tasks --group gocourse
./gradlew courseInfo -q

Output:

Gocourse tasks
--------------
courseInfo - Prints information about this project.

Project: grade-calculator
Java toolchain: 25

How it works:

  • group and description make the task appear in ./gradlew tasks under its own heading.
  • Values are read into local variables outside doLast. Task actions should not reach back into project while running; this keeps the task compatible with the configuration cache, which reuses the configured task graph between builds.
  • -q (quiet) hides Gradle's own log lines, so only the task's output is shown.

Connect Gradle Tasks With dependsOn and finalizedBy

Tasks declare their order with relationships instead of running in file order.

MethodMeaning
dependsOn(x)Run x first, always
finalizedBy(x)Run x afterwards, even if this task fails
mustRunAfter(x)If both are selected, run this one after x (does not add x)
tasks.register("prepareData") {
    doLast { println("1. Preparing data") }
}

tasks.register("cleanupTemp") {
    doLast { println("3. Removing temporary files") }
}

tasks.register("report") {
    dependsOn("prepareData")
    finalizedBy("cleanupTemp")
    doLast { println("2. Writing report") }
}
./gradlew report -q

Output:

1. Preparing data
2. Writing report
3. Removing temporary files

How it works:

  • Asking for report pulls in prepareData before it and cleanupTemp after it.
  • Each task runs at most once per build, even if several tasks depend on it.
  • finalizedBy suits cleanup work such as stopping a test server, because it runs even when report fails.

Use Built-In Task Types: Copy and Zip

Gradle ships typed tasks for common jobs. You configure them instead of writing actions yourself, and they get up-to-date checks for free.

tasks.register<Copy>("copyConfig") {
    from("config")                                   // config/app.properties
    into(layout.buildDirectory.dir("staging/config"))
}

tasks.register<Zip>("zipSources") {
    from("src/main/java")
    archiveFileName = "sources.zip"
    destinationDirectory = layout.buildDirectory.dir("dist")
}
./gradlew copyConfig zipSources --console=plain
./gradlew zipSources --console=plain
ls build/dist build/staging/config

Output:

> Task :copyConfig
> Task :zipSources

BUILD SUCCESSFUL in 590ms
2 actionable tasks: 2 executed
> Task :zipSources UP-TO-DATE

BUILD SUCCESSFUL in 402ms
1 actionable task: 1 up-to-date
build/dist:
sources.zip

build/staging/config:
app.properties

How it works:

  • tasks.register<Copy> creates a task of type Copy. from and into are both its inputs and outputs, which Gradle tracks automatically.
  • layout.buildDirectory points to build/, even if someone changes the build directory, so avoid hard-coding "build/...".
  • The second zipSources is UP-TO-DATE because no source file changed.

Configure Built-In Java Tasks

Plugins create tasks such as compileJava, test and jar. You change their settings through tasks.named or the typed shortcut tasks.withType.

tasks.withType<JavaCompile>().configureEach {
    options.encoding = "UTF-8"
    options.compilerArgs.addAll(listOf("-Xlint:all", "-Werror"))
}

tasks.test {
    useJUnitPlatform()
    maxParallelForks = 2                       // run test classes in 2 JVMs
}

tasks.jar {
    manifest {
        attributes("Implementation-Title" to project.name,
                   "Implementation-Version" to project.version)
    }
}
./gradlew jar -q
unzip -p build/libs/grade-calculator-1.0.0.jar META-INF/MANIFEST.MF

Output:

Manifest-Version: 1.0
Implementation-Title: grade-calculator
Implementation-Version: 1.0.0

How it works:

  • withType<JavaCompile>() covers both compileJava and compileTestJava. configureEach applies the settings lazily, only to tasks that are actually used.
  • -Xlint:all -Werror makes compiler warnings fail the build, as in Maven Plugins.
  • The manifest attributes end up in META-INF/MANIFEST.MF. Lesson Build Executable JAR adds Main-Class so the JAR runs with java -jar.

Create a Gradle Multi-Project Build

A multi-project build splits an application into subprojects that are built together. settings.gradle.kts lists them, and one subproject depends on another with project(":name").

// settings.gradle.kts
rootProject.name = "library-system"
include("core", "app")
// app/build.gradle.kts (excerpt)
dependencies {
    implementation(project(":core"))
}
./gradlew projects

Output:

> Task :projects

Projects:

------------------------------------------------------------
Root project 'library-system'
------------------------------------------------------------

Root project 'library-system'
+--- Project ':app'
\--- Project ':core'

How it works:

  • Each subproject is a folder with its own build.gradle.kts and src/.
  • Task paths include the project: :core:test runs only core's tests, while plain test runs test in every project.
  • Gradle builds :core before :app because of the project(":core") dependency. With org.gradle.parallel=true, independent projects build at the same time.

Note: When several subprojects share the same settings (toolchain, test setup), large builds move them into a convention plugin in buildSrc or an included build. Avoid allprojects { } blocks; they couple projects together and slow down configuration.


Real-World Example: Gradle Build for a Library System

This build has two subprojects. core holds the library logic and its tests. app is a command-line app that depends on core and prints a version number generated by a custom task during the build.

library-system/
├── settings.gradle.kts
├── gradle.properties
├── core/
│   ├── build.gradle.kts
│   └── src/main/java/com/gocourse/library/core/{Book.java, Library.java}
│       src/test/java/com/gocourse/library/core/LibraryTest.java
└── app/
    ├── build.gradle.kts
    └── src/main/java/com/gocourse/library/app/LibraryApp.java
// settings.gradle.kts
rootProject.name = "library-system"
include("core", "app")
# gradle.properties
version=1.2.0
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.configuration-cache=true
// core/build.gradle.kts
plugins {
    `java-library`
}

repositories { mavenCentral() }

java {
    toolchain { languageVersion = JavaLanguageVersion.of(25) }
}

dependencies {
    testImplementation(platform("org.junit:junit-bom:6.1.3"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test { useJUnitPlatform() }
// app/build.gradle.kts
plugins {
    application
}

repositories { mavenCentral() }

java {
    toolchain { languageVersion = JavaLanguageVersion.of(25) }
}

dependencies {
    implementation(project(":core"))
}

application {
    mainClass = "com.gocourse.library.app.LibraryApp"
}

// Custom task: writes build-info.properties into a generated resources folder
val generateBuildInfo by tasks.registering {
    group = "gocourse"
    description = "Generates build-info.properties with the app version."

    val appVersion = project.version.toString()
    val outputDir = layout.buildDirectory.dir("generated/build-info")
    inputs.property("version", appVersion)
    outputs.dir(outputDir)

    doLast {
        val infoFile = outputDir.get().file("build-info.properties").asFile
        infoFile.parentFile.mkdirs()
        infoFile.writeText("app.version=$appVersion\n")
    }
}

sourceSets.main {
    resources.srcDir(generateBuildInfo)   // also makes processResources depend on it
}
// core/src/main/java/com/gocourse/library/core/Book.java
package com.gocourse.library.core;

public record Book(String isbn, String title, String author) {}
// core/src/main/java/com/gocourse/library/core/Library.java
package com.gocourse.library.core;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Library {
    private final Map<String, Book> booksByIsbn = new LinkedHashMap<>();
    private final List<String> borrowedIsbns = new ArrayList<>();

    public void add(Book book) {
        booksByIsbn.put(book.isbn(), book);
    }

    /** Returns the borrowed book, or throws if it is unknown or already out. */
    public Book borrow(String isbn) {
        Book book = booksByIsbn.get(isbn);
        if (book == null) {
            throw new IllegalArgumentException("No book with ISBN " + isbn);
        }
        if (borrowedIsbns.contains(isbn)) {
            throw new IllegalStateException(book.title() + " is already borrowed");
        }
        borrowedIsbns.add(isbn);
        return book;
    }

    public List<Book> available() {
        return booksByIsbn.values().stream()
                .filter(book -> !borrowedIsbns.contains(book.isbn()))
                .toList();
    }
}
// core/src/test/java/com/gocourse/library/core/LibraryTest.java
package com.gocourse.library.core;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

class LibraryTest {

    @Test
    void borrowedBookIsNoLongerAvailable() {
        Library library = new Library();
        library.add(new Book("111", "Java Basics", "Asha Kumar"));
        library.add(new Book("222", "Gradle Guide", "Ravi Shankar"));

        library.borrow("111");

        assertEquals(1, library.available().size());
        assertEquals("Gradle Guide", library.available().get(0).title());
    }

    @Test
    void sameBookCannotBeBorrowedTwice() {
        Library library = new Library();
        library.add(new Book("111", "Java Basics", "Asha Kumar"));
        library.borrow("111");
        assertThrows(IllegalStateException.class, () -> library.borrow("111"));
    }
}
// app/src/main/java/com/gocourse/library/app/LibraryApp.java
package com.gocourse.library.app;

import com.gocourse.library.core.Book;
import com.gocourse.library.core.Library;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class LibraryApp {
    public static void main(String[] args) throws IOException {
        System.out.println("Library System " + appVersion());

        Library library = new Library();
        library.add(new Book("111", "Java Basics", "Asha Kumar"));
        library.add(new Book("222", "Gradle Guide", "Ravi Shankar"));
        library.add(new Book("333", "Clean Tests", "Meena Iyer"));

        Book borrowed = library.borrow("222");
        System.out.println("Borrowed: " + borrowed.title());

        System.out.println("Available books:");
        library.available().forEach(book ->
                System.out.println(" - " + book.title() + " by " + book.author()));
    }

    private static String appVersion() throws IOException {
        Properties info = new Properties();
        try (InputStream in = LibraryApp.class.getResourceAsStream("/build-info.properties")) {
            info.load(in);
        }
        return info.getProperty("app.version");
    }
}

Build everything, then run the app twice:

./gradlew build
./gradlew :app:run --console=plain
./gradlew :app:run -q

Output (shortened):

BUILD SUCCESSFUL in 6s
Configuration cache entry stored.
> Task :core:compileJava UP-TO-DATE
> Task :app:generateBuildInfo UP-TO-DATE
> Task :app:processResources UP-TO-DATE
> Task :app:compileJava UP-TO-DATE
> Task :core:jar UP-TO-DATE
> Task :app:run
Library System 1.2.0
Borrowed: Gradle Guide
Available books:
 - Java Basics by Asha Kumar
 - Clean Tests by Meena Iyer

BUILD SUCCESSFUL in 1s
Configuration cache entry stored.
Library System 1.2.0
Borrowed: Gradle Guide
Available books:
 - Java Basics by Asha Kumar
 - Clean Tests by Meena Iyer

How it works:

  1. Initialization. settings.gradle.kts includes core and app; gradle.properties sets version=1.2.0 for every project and turns on parallel builds, the build cache and the configuration cache.
  2. Project dependency. implementation(project(":core")) puts core's classes on the app's classpath, so :core:compileJava always runs (or is up to date) before :app:compileJava.
  3. Generated resources. Passing the generateBuildInfo task to resources.srcDir both adds its output folder to the resources and makes processResources depend on it. No dependsOn is needed.
  4. Correct up-to-date checks. The task declares the version as an input and the folder as an output. Change version in gradle.properties and only generateBuildInfo, processResources and the tasks after them run again.
  5. Configuration cache. All project values are captured before doLast, so Gradle can store the configured build. The third command reuses that cache and skips the configuration phase entirely.

The core subproject uses the java-library plugin, which matters for how its own dependencies are shared with app. That is the topic of the next lesson, Gradle Dependencies.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Gradle Build and get answers drawn from it.

Signed-in readers only.