Fix: Gradle Build Failed – Could Not Resolve Dependencies or Compilation Error
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 :appOr 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 17Or 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.
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 compileClasspathOr for a specific module:
gradle :app:dependencies --configuration debugCompileClasspathIf 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.0Force 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 --versionLook 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-teminstantly setsJAVA_HOMEandPATHwithout 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 --stopThen run the build again:
gradle clean buildCheck the status of running daemons:
gradle --statusThis 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:+HeapDumpOnOutOfMemoryErrorThe 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 buildIf 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-dependenciesThis 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 cleanOr manually:
rm -rf build/
# For multi-module projects, clean all subproject build dirs
rm -rf */build/Common Mistake: Running
--refresh-dependencieson 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.0Or:
> Failed to find target with hash string 'android-34' in: /Users/you/Library/Android/sdkFix 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 --licensesVerify your local.properties points to the correct SDK:
sdk.dir=/Users/you/Library/Android/sdkOn Windows:
sdk.dir=C\:\\Users\\you\\AppData\\Local\\Android\\SdkEnsure ANDROID_HOME or ANDROID_SDK_ROOT is set:
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-toolsEnvironment 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.zipFix 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 --stacktraceThis prints the full exception, including the line number in your build script where the syntax error occurred. For even more output:
gradle build --info --stacktraceOr maximum verbosity:
gradle build --debugFix 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:
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.
Missing
apivs.implementationvisibility. If Module A depends on Module B usingimplementation, and Module C depends on Module A, Module C cannot see Module B’s classes. Useapiif 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
}- Inconsistent versions across modules. Use a version catalog or
buildSrcto 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=passwordBoth 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 changeitFor 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.logSearch 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 --scanAccept 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 buildCheck the wrapper version in gradle/wrapper/gradle-wrapper.properties:
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zipIf this points to an old Gradle version that is incompatible with your plugins or JDK, update it:
./gradlew wrapper --gradle-version 8.7Clean 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-dependenciesThis 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.
Solo developer based in Japan. Every solution is cross-referenced with official documentation and tested before publishing.
Was this article helpful?
Related Articles
Fix: java.lang.ClassNotFoundException (Class Not Found at Runtime)
How to fix Java ClassNotFoundException at runtime by resolving missing dependencies, classpath issues, Maven/Gradle configuration, JDBC drivers, classloader problems, and Java module system errors.
Fix: Java ClassCastException: class X cannot be cast to class Y
How to fix Java ClassCastException by using instanceof checks, fixing generic type erasure, resolving ClassLoader conflicts, correcting raw types, and using pattern matching in Java 16+.
Fix: Java ConcurrentModificationException
How to fix Java ConcurrentModificationException caused by modifying a collection while iterating, HashMap concurrent access, stream operations, and multi-threaded collection usage.
Fix: Java NoSuchMethodError
How to fix Java NoSuchMethodError caused by classpath conflicts, incompatible library versions, wrong dependency scope, shaded JARs, and compile vs runtime version mismatches.