Gradle finds wrong JAVA_HOME even though it's correctly set

When trying to run gradle, I get the following error:

# gradle

ERROR: JAVA_HOME is set to an invalid directory: /usr/lib/jvm/default-java

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.

However, when I check the JAVA_HOME variable I get:

# echo $JAVA_HOME 
/usr/lib/jvm/java-7-oracle

My JAVA_HOME is defined in .bashrc and I have double checked that it is set as the source.

Running java -version also confirms that JAVA_HOME is set correctly and is on the PATH.

# java -version
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)

I have also checked that /usr/bin/java symlinks to /etc/alternatives/java which in turn correctly symlinks to /usr/lib/jvm/java-7-oracle/jre/bin/java

Additionally I've checked that there are no duplicate JAVA_HOME definitions in .bash_profile or /etc/profile.

So my question is how/why does Gradle find /usr/lib/jvm/default-java, and more importantly how do I point it to the correct directory?

Other programs which require the JDK work fine, so I think its a Gradle issue. I've also tried reinstalling Gradle which made no difference.

I'm running 64bit Xubuntu (Ubuntu 13.10 base)


Solution 1:

Turns out that the particular Gradle binary I downloaded from the Ubuntu 13.10 repository itself tries to export JAVA_HOME. Thanks to Lucas for suggesting this.

/usr/bin/gradle line 70:

export JAVA_HOME=/usr/lib/jvm/default-java

Commenting this line out solves the problem, and Gradle finds the correct path to the Java binary.

If you just download the binary from their website it does not have this problem, It's an issue with the Ubuntu repo version. There also seem to be some other issues with 13.10 version.

Solution 2:

add a symbolic link

sudo ln -s /usr/lib/jvm/java-7-oracle /usr/lib/jvm/default-java

Solution 3:

Solution is to make JAVA_HOME == dir above bin where javac lives as in

type javac

javac is /usr/bin/javac   # now check if its just a symlink

ls -la /usr/bin/javac 

/usr/bin/javac -> /etc/alternatives/javac   # its a symlink so check again

ls -la /etc/alternatives/javac  # now check if its just a symlink

/etc/alternatives/javac -> /usr/lib/jvm/java-8-openjdk-amd64/bin/javac

OK so finally found the bin above actual javac so do this

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
export PATH=$JAVA_HOME/bin:$PATH

above can be simplified and generalized to

which javac >/dev/null 2>&1 || die "ERROR: no 'javac' command could be found in your PATH"
export JAVA_HOME=$(dirname $(dirname $(readlink -f $(which javac)  )))

Solution 4:

For me this error was due to the reason Gradle as installed as sudo and I was trying as default user to run Gradle.

Try:

sudo gradle -version

or

sudo gradle -v