Skip to content

Fix: Gradle Build Failed – Could Not Resolve Dependencies or Compilation Error

FixDevs · (Updated: )

Part of:  Java & JVM Errors

Quick Answer

How to fix Gradle build failures including dependency resolution errors, compilation failures, incompatible Java versions, and daemon issues.

The Error

Your Gradle build fails with one of these errors:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileJava'.
> Could not resolve all files for configuration ':app:compileClasspath'.
   > Could not find com.example:some-library:2.5.0.
     Searched in the following locations:
       - https://repo.maven.apache.org/maven2/com/example/some-library/2.5.0/some-library-2.5.0.pom
     Required by:
         project :app

Or a compilation failure:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileJava'.
> Compilation failed; see the compiler error output for details.

error: source release 17 requires target release 17

Or an Android variant:

Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> Could not resolve all task dependencies for configuration ':app:debugCompileClasspath'.
   > Could not find com.google.android.material:material:1.12.0.

Or a cryptic daemon failure:

FAILURE: Build failed with an exception.

* What went wrong:
Gradle build daemon disappeared unexpectedly (it may have been killed or may have crashed)

The build cannot complete because Gradle is unable to resolve dependencies, compile your source code, or maintain a stable build process.

Why This Happens

Gradle build failures fall into several categories, and understanding which one you are dealing with determines the fix.

Dependency resolution failures occur when Gradle cannot download or locate a declared dependency. This can happen because the dependency does not exist at the specified coordinates (typo in the group ID, artifact ID, or version), the repository hosting it is not declared in your build file, or a network issue prevents Gradle from reaching the repository. Transitive dependency conflicts, where two libraries require incompatible versions of a shared dependency, also fall into this category. If you have worked with npm, this is conceptually similar to the dependency tree conflicts described in Fix: npm ERESOLVE unable to resolve dependency tree.

Compilation failures due to Java version mismatches happen when your project’s sourceCompatibility or targetCompatibility setting targets a Java version that does not match the JDK installed on your system. If your build.gradle declares sourceCompatibility = '17' but your JAVA_HOME points to JDK 11, the compiler cannot process Java 17 language features and the build fails.

Gradle daemon issues are a frequent source of confusing failures. The Gradle daemon is a long-running background process that speeds up builds by keeping the JVM warm. But if the daemon runs out of memory, encounters a JVM crash, or becomes corrupted after a Gradle version upgrade, it can cause builds to fail with unhelpful error messages. Stale daemons from older Gradle versions can conflict with the current version.

Cache corruption happens when Gradle’s local dependency cache (typically ~/.gradle/caches/) gets into an inconsistent state. This can occur after interrupted downloads, disk space issues, or file system errors. Gradle trusts the cache and does not re-verify artifacts unless forced.

Build script syntax errors in build.gradle or build.gradle.kts cause failures before any task even runs. A missing closing brace, incorrect method call, or invalid Groovy/Kotlin syntax breaks the build script evaluation phase.

Diagnostic Timeline

Gradle’s failure output is notoriously verbose. The most common reaction is to rerun with --rerun-tasks and hope for the best. That fixes almost nothing because Gradle’s error messages bury the real cause under several layers of task summaries. Walk through it like an experienced JVM build engineer would.

First reaction: --rerun-tasks or clean build. This rebuilds without using the build cache. It helps for genuine cache corruption but does nothing for compilation errors, dependency resolution failures, daemon crashes, or JVM memory problems. If your second run fails with the same error, you wasted two minutes.

Second reaction: skim the bottom of the output. Gradle prints a final summary like Execution failed for task ':app:compileJava'. The summary names the task that failed, not the root cause. The actual error is usually higher in the output. Scroll up and look for the first * What went wrong: or Caused by: block. That is where the real diagnostic lives.

Third reaction: rerun with --stacktrace, then --info, then --scan. This is the right sequence and most developers stop at the first one. --stacktrace shows the full Java exception. --info adds Gradle’s internal logging — dependency resolution decisions, configuration cache hits, task input/output details. --scan uploads a complete build trace to a Gradle-hosted web UI that shows every dependency, every task duration, and every error in a navigable form. For an unfamiliar failure mode, --scan is the fastest path to the root cause.

Fourth reaction: blame the daemon. Daemon crashes have a specific signature: Gradle build daemon disappeared unexpectedly or OutOfMemoryError during a long compilation. If you see those exact strings, the daemon is the problem and you fix it by raising org.gradle.jvmargs in gradle.properties (default 512MB is far too small for Android or large multi-module projects — 2GB to 4GB is normal). If you do not see those strings, the daemon is not your problem and stopping it with gradle --stop only adds startup overhead to your next build.

Fifth reaction: Kotlin DSL vs Groovy DSL message confusion. A syntax error in build.gradle.kts produces a Kotlin compiler error from the buildscript itself, which can look like a project compilation error if you do not read the location carefully. Check whether the file path in the error points to a .kts build script or to one of your source files. If it points to .kts, you have a buildscript syntax issue (often a missing parenthesis or the wrong assignment style — set vs = vs method call).

Actual root cause check. Categorize the failure first:

  • Could not find ... — Dependency resolution. Check repositories, coordinates, and proxy configuration.
  • Compilation failed with line numbers in your source — Real Java/Kotlin error. Read it like any compile error.
  • source release N requires target release N — Java version mismatch between project and JDK.
  • Could not determine the dependencies of task — Configuration phase failure, usually a buildscript or settings.gradle issue.
  • daemon disappeared or OutOfMemoryError — Daemon memory or JVM crash.
  • The Daemon will expire — Memory pressure warning, not yet a failure. Increase heap proactively.

Match the message to the category before applying any fix below. Wrong category, wrong fix, wasted time.

Fix 1: Resolve Missing Dependencies

If Gradle reports Could not find followed by a dependency coordinate, the artifact is not available in any of the declared repositories.

Check your repository declarations in build.gradle:

repositories {
    mavenCentral()
    google()  // Required for Android and Google libraries
}

Or in build.gradle.kts:

repositories {
    mavenCentral()
    google()
}

Many projects forget to declare google() when using AndroidX or Material Design libraries. If your dependency is hosted on a private or less common repository, you need to add it explicitly:

repositories {
    mavenCentral()
    google()
    maven {
        url 'https://jitpack.io'
    }
    maven {
        url 'https://your-company.com/maven-repo'
        credentials {
            username = project.findProperty('repoUser') ?: ''
            password = project.findProperty('repoPassword') ?: ''
        }
    }
}

Verify the dependency coordinates are correct. A single typo in the group ID, artifact ID, or version will cause a resolution failure. Search for the correct coordinates on Maven Central or Google’s Maven Repository:

dependencies {
    // WRONG — typo in groupId
    implementation 'com.gogle.code.gson:gson:2.11.0'

    // CORRECT
    implementation 'com.google.code.gson:gson:2.11.0'
}

Check the dependency tree for conflicts:

gradle dependencies --configuration compileClasspath

Or for a specific module:

gradle :app:dependencies --configuration debugCompileClasspath

If you see version conflicts indicated by -> in the output, Gradle is silently upgrading a transitive dependency, which can cause runtime issues:

com.fasterxml.jackson.core:jackson-databind:2.14.0 -> 2.17.0

Force a specific version if needed:

configurations.all {
    resolutionStrategy.force 'com.fasterxml.jackson.core:jackson-databind:2.17.0'
}

Fix 2: Fix Java Version Mismatches (sourceCompatibility / targetCompatibility)

If you see errors like source release 17 requires target release 17 or invalid source release: 21, your JDK does not match the project’s language level.

Check which JDK Gradle is using:

gradle --version

Look at the JVM line in the output. It shows the Java version Gradle is running on.

Check your current JAVA_HOME:

# Linux/macOS
echo $JAVA_HOME

# Windows
echo %JAVA_HOME%

Set the correct Java version in your build file:

// build.gradle
java {
    sourceCompatibility = JavaVersion.VERSION_17
    targetCompatibility = JavaVersion.VERSION_17
}

Or in build.gradle.kts:

java {
    sourceCompatibility = JavaVersion.VERSION_17
    targetCompatibility = JavaVersion.VERSION_17
}

For Android projects, configure it in the android block:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }
    kotlinOptions {
        jvmTarget = '17'
    }
}

Use Gradle toolchains to decouple the JDK used for building from the JDK running Gradle itself. This is the recommended approach for modern projects:

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

With toolchains, Gradle automatically downloads and uses the specified JDK version, regardless of your JAVA_HOME setting. This eliminates version mismatch issues across team members and CI environments.

If your Java version issue leads to classes not being found at runtime, you may also want to read Fix: java.lang.ClassNotFoundException for classpath troubleshooting.

Pro Tip: If you manage multiple JDK versions on your machine, use a tool like SDKMAN (Linux/macOS) or Jabba (cross-platform) to switch between them. Running sdk use java 17.0.11-tem instantly sets JAVA_HOME and PATH without manual editing. On CI servers, configure the JDK version in your pipeline definition rather than relying on the system default, so builds are reproducible regardless of what else is installed on the agent.

Fix 3: Stop and Restart the Gradle Daemon

If your builds fail with daemon crashes, mysterious disappearances, or OutOfMemoryError during compilation, the Gradle daemon is the likely culprit.

Stop all running daemons:

gradle --stop

Then run the build again:

gradle clean build

Check the status of running daemons:

gradle --status

This shows all daemon processes, their versions, and their status (IDLE, BUSY, or STOPPED). If you see daemons from multiple Gradle versions, stop them all.

Increase daemon memory if builds fail with OutOfMemoryError: Java heap space or GC overhead limit exceeded. Edit gradle.properties (either in the project root or ~/.gradle/gradle.properties):

org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError

The default daemon memory is 512 MB, which is often too low for large projects, especially Android builds. For large multi-module projects, 2-4 GB is common.

If your Java process is running out of memory during the build, Fix: Java OutOfMemoryError covers JVM memory tuning in depth.

Disable the daemon temporarily to rule it out as the problem:

gradle --no-daemon clean build

If the build succeeds without the daemon, the issue is daemon-specific (usually memory or version conflicts).

Fix 4: Clear the Gradle Cache (—refresh-dependencies)

If Gradle resolved a dependency before but the cached version is corrupted or incomplete, it will reuse the broken cache entry instead of re-downloading.

Force Gradle to re-download all dependencies:

gradle build --refresh-dependencies

This tells Gradle to ignore the cached dependency metadata and check all remote repositories again. It does not delete the cache, but it forces re-validation.

For a more thorough reset, delete the cache manually:

# Delete the entire Gradle cache (re-downloads everything on next build)
rm -rf ~/.gradle/caches/

# Delete only the dependency cache (preserves build caches and other data)
rm -rf ~/.gradle/caches/modules-2/

On Windows:

# PowerShell
Remove-Item -Recurse -Force "$env:USERPROFILE\.gradle\caches\"

Delete the project-level build directory as well:

gradle clean

Or manually:

rm -rf build/
# For multi-module projects, clean all subproject build dirs
rm -rf */build/

Common Mistake: Running --refresh-dependencies on every build is not a solution. It significantly slows down builds because Gradle has to re-check every artifact against remote repositories. Use it once to fix a corrupted cache, then investigate why the cache was corrupted in the first place (interrupted downloads, disk space issues, concurrent builds writing to the same cache).

Fix 5: Fix Android SDK and Build Tool Issues

Android projects have additional dependency layers: the Android SDK, build tools, and platform versions. Missing or mismatched SDK components cause build failures.

Common Android SDK error:

> Failed to find Build Tools revision 34.0.0

Or:

> Failed to find target with hash string 'android-34' in: /Users/you/Library/Android/sdk

Fix by installing the required SDK components:

# List installed and available packages
sdkmanager --list

# Install specific build tools
sdkmanager "build-tools;34.0.0"

# Install a platform version
sdkmanager "platforms;android-34"

Or accept all licenses if that is the issue:

sdkmanager --licenses

Verify your local.properties points to the correct SDK:

sdk.dir=/Users/you/Library/Android/sdk

On Windows:

sdk.dir=C\:\\Users\\you\\AppData\\Local\\Android\\Sdk

Ensure ANDROID_HOME or ANDROID_SDK_ROOT is set:

export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Environment variable configuration issues are a common cause of build failures across many tools. If you suspect your environment variables are not being picked up correctly, see Fix: Environment Variable Is Undefined for debugging techniques.

Update the Android Gradle Plugin (AGP) and Gradle version together. AGP versions are tightly coupled to Gradle versions. If you upgrade one, check the compatibility table:

// build.gradle (project level)
plugins {
    id 'com.android.application' version '8.5.0' apply false
}
# gradle/wrapper/gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip

Fix 6: Fix build.gradle Syntax Errors

Gradle build scripts are Groovy (.gradle) or Kotlin (.gradle.kts) code. Syntax errors in these files cause the build to fail during the configuration phase, before any task runs.

Groovy DSL common mistakes:

// WRONG — missing quotes around version
dependencies {
    implementation com.google.code.gson:gson:2.11.0
}

// CORRECT
dependencies {
    implementation 'com.google.code.gson:gson:2.11.0'
}
// WRONG — using = instead of method call for dependencies
dependencies {
    implementation = 'com.google.code.gson:gson:2.11.0'
}

// CORRECT
dependencies {
    implementation 'com.google.code.gson:gson:2.11.0'
}
// WRONG — missing closing brace
android {
    compileSdkVersion 34
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 24
    // } <-- missing this

// CORRECT
android {
    compileSdkVersion 34
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 24
    }
}

Kotlin DSL common mistakes:

// WRONG — using single quotes (Kotlin uses double quotes)
dependencies {
    implementation('com.google.code.gson:gson:2.11.0')
}

// CORRECT
dependencies {
    implementation("com.google.code.gson:gson:2.11.0")
}

Validate your build script by running with --stacktrace:

gradle build --stacktrace

This prints the full exception, including the line number in your build script where the syntax error occurred. For even more output:

gradle build --info --stacktrace

Or maximum verbosity:

gradle build --debug

Fix 7: Fix Multi-Module Project Issues

Multi-module projects have a settings.gradle file that declares subprojects and a root build.gradle that may apply shared configuration. Misconfiguration at either level causes build failures.

Ensure all modules are declared in settings.gradle:

// settings.gradle
rootProject.name = 'my-app'
include ':app', ':core', ':data', ':network'

If a module is not included here, Gradle does not know it exists and any references to it will fail.

Fix inter-module dependency declarations:

// app/build.gradle
dependencies {
    implementation project(':core')
    implementation project(':data')
}

Common multi-module errors:

  1. Circular dependencies. Module A depends on Module B, and Module B depends on Module A. Gradle will report this explicitly. The fix is to extract shared code into a third module that both depend on.

  2. Missing api vs. implementation visibility. If Module A depends on Module B using implementation, and Module C depends on Module A, Module C cannot see Module B’s classes. Use api if you need transitive visibility:

// core/build.gradle
dependencies {
    api 'com.google.code.gson:gson:2.11.0'         // visible to consumers of :core
    implementation 'com.squareup.okio:okio:3.9.0'   // hidden from consumers
}
  1. Inconsistent versions across modules. Use a version catalog or buildSrc to centralize dependency versions:
# gradle/libs.versions.toml
[versions]
gson = "2.11.0"
okhttp = "4.12.0"

[libraries]
gson = { module = "com.google.code.gson:gson", version.ref = "gson" }
okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }

Then reference them in any module’s build.gradle.kts:

dependencies {
    implementation(libs.gson)
    implementation(libs.okhttp)
}

Fix 8: Fix Proxy and Repository Configuration

If you are behind a corporate proxy or firewall, Gradle cannot reach Maven Central or Google’s repository without proxy configuration.

Configure the proxy in ~/.gradle/gradle.properties:

systemProp.http.proxyHost=proxy.company.com
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=username
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=localhost|127.0.0.1|*.company.com

systemProp.https.proxyHost=proxy.company.com
systemProp.https.proxyPort=8080
systemProp.https.proxyUser=username
systemProp.https.proxyPassword=password

Both http and https must be configured separately. Maven Central and most repositories use HTTPS, so only configuring http is not enough.

If your company uses a private artifact repository (Artifactory, Nexus, etc.), replace the default repositories:

repositories {
    maven {
        url 'https://artifactory.company.com/maven-virtual'
        credentials {
            username = project.findProperty('artifactoryUser') ?: System.getenv('ARTIFACTORY_USER')
            password = project.findProperty('artifactoryPassword') ?: System.getenv('ARTIFACTORY_PASSWORD')
        }
    }
}

Diagnose connectivity issues:

# Test if Gradle can reach Maven Central
gradle build --info 2>&1 | grep -i "download"

# Test connectivity directly
curl -I https://repo.maven.apache.org/maven2/

If curl works but Gradle does not, the issue is in Gradle’s proxy or SSL configuration, not your network.

SSL certificate issues with corporate proxies that perform MITM inspection require importing the proxy’s CA certificate into the JDK’s truststore:

keytool -import -trustcacerts -alias company-proxy \
    -file company-ca.crt \
    -keystore $JAVA_HOME/lib/security/cacerts \
    -storepass changeit

For Docker-based builds that also need proxy configuration, see Fix: docker compose up errors for container-level network troubleshooting.

Still Not Working?

Run with full diagnostic output

If none of the above fixes match your situation, run the build with maximum logging to capture every detail:

gradle build --stacktrace --info 2>&1 | tee gradle-debug.log

Search the log file for the first FAILURE or ERROR line. Gradle often prints the root cause deep in the output, followed by a more generic error message at the end. The first error is usually the real one.

Build scan

Gradle’s build scan feature uploads detailed build information to a web interface for analysis:

gradle build --scan

Accept the terms of service when prompted, and Gradle prints a URL with a full breakdown of the build: task execution, dependency resolution, performance, and failure details. This is especially useful when sharing build failures with teammates or asking for help online.

Gradle wrapper version mismatch

If the project includes a Gradle wrapper (gradlew / gradlew.bat), always use it instead of your globally installed gradle:

# CORRECT — uses the wrapper
./gradlew build

# WRONG — may use a different Gradle version
gradle build

Check the wrapper version in gradle/wrapper/gradle-wrapper.properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip

If this points to an old Gradle version that is incompatible with your plugins or JDK, update it:

./gradlew wrapper --gradle-version 8.7

Clean everything and start fresh

When all else fails, a full reset often resolves the issue:

# Stop all daemons
./gradlew --stop

# Delete project build directories
./gradlew clean

# Delete Gradle's dependency cache
rm -rf ~/.gradle/caches/

# Delete the local build cache
rm -rf ~/.gradle/build-cache/

# Re-download the wrapper distribution
rm -rf ~/.gradle/wrapper/dists/

# Rebuild
./gradlew build --refresh-dependencies

This is the nuclear option. It forces Gradle to re-download everything: the Gradle distribution itself, all dependencies, and all cached build outputs. It takes time but eliminates any possibility of stale or corrupted cached state.

Check file permissions

On Linux and macOS, incorrect file permissions on the gradlew script or the ~/.gradle directory can cause failures:

# Make the wrapper executable
chmod +x gradlew

# Fix ownership of the Gradle home directory
chown -R $(whoami) ~/.gradle/

CI-specific issues

CI environments (GitHub Actions, Jenkins, GitLab CI) introduce additional variables: different users, limited disk space, network restrictions, and parallel builds sharing the same cache.

# GitHub Actions — cache Gradle dependencies
- uses: actions/cache@v4
  with:
    path: |
      ~/.gradle/caches
      ~/.gradle/wrapper
    key: gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
    restore-keys: gradle-

If CI builds fail but local builds succeed, check whether the CI agent has the correct JDK installed, sufficient memory allocated to the build process, and network access to your repositories. If your CI also runs Docker-based steps, the build environment may need additional configuration beyond Gradle itself.

Configuration cache compatibility issues

Gradle 7+ ships a configuration cache that serializes the result of the configuration phase. Plugins that read mutable state at configuration time (system properties, environment variables, project properties resolved lazily) often break under the configuration cache and produce errors like cannot serialize Gradle script object or unsupported task action. Either disable the cache temporarily (--no-configuration-cache) to confirm it is the cause, or upgrade the offending plugin to a version that declares compatibility. Plugin authors have been steadily adding support — pin to recent versions when possible. Related plugin-version mismatches show up in Java ClassCastException failures when two plugins each ship their own copy of the same library and Gradle resolves to a version neither expected.

Kotlin Multiplatform and Compose plugins introduce version constraints

If you use Kotlin Multiplatform, Jetpack Compose, or KSP, the Kotlin compiler version, the Compose compiler version, the Android Gradle Plugin version, and the Gradle distribution version are all tightly coupled. A version bump in any one of them can break the others. JetBrains and Google publish a compatibility matrix for each combination — check it before changing any version. Mismatches typically surface as Module was compiled with an incompatible version of Kotlin errors during the Kotlin compilation task. This kind of cross-tool version pinning also shows up in TypeScript cannot find module errors when a TypeScript version no longer matches the type definitions for a library.

Network proxy and certificate issues in corporate environments

If gradle build works at home but fails on the corporate network with PKIX path building failed or unable to find valid certification path to requested target, the corporate proxy is performing TLS interception and Gradle’s JDK does not trust the proxy’s CA certificate. Import the corporate CA into the JDK truststore with keytool -import as shown earlier, or set -Djavax.net.ssl.trustStore=... system properties in org.gradle.jvmargs. The same certificate trust failure also breaks Java OutOfMemoryError-style diagnostic uploads and any other HTTPS-dependent JVM tool.

Confirm wrapper checksum verification has not corrupted

The Gradle wrapper validates its downloaded distribution against a SHA-256 checksum stored in gradle/wrapper/gradle-wrapper.properties. If the checksum is wrong (because someone copied the URL but not the checksum, or because the file was edited) the wrapper refuses to use the downloaded distribution and the build fails before any task runs. Verify the line distributionSha256Sum=... matches the official published checksum for your declared distributionUrl. Mismatched or missing checksums also produce silent failures similar to Java IllegalArgumentException cases where the input looks valid but a validation layer rejects it without a clear message.

Watch for parallel build conflicts on shared caches

If you run multiple Gradle builds concurrently (parallel CI jobs sharing a cache mount, two terminal windows in the same repo, a background daemon plus an active foreground build), they can corrupt each other’s writes to ~/.gradle/caches. Symptoms include cannot lock file hash cache and intermittent dependency not found errors that disappear on retry. Either give each parallel build its own GRADLE_USER_HOME directory or serialize the jobs. CI providers usually let you key the cache by branch and job so two concurrent jobs do not collide. This kind of shared-state corruption looks like apt-get unable to locate package failures during Docker builds where two layers race to update the same package index.

F

FixDevs

Solo developer based in Japan. Every solution is cross-referenced with official documentation and tested before publishing.

Was this article helpful?

Related Articles