24 June 2010

Dynamically Setting JAVA_HOME on Mac OS X

This was a new discovery to me today, so please ignore if this is widely used and known.

On Mac OS X, there is a very specific, managed directory structure for the various Java versions that are installed.  The general directory is "/System/Library/Frameworks/JavaVM.framework/".  For those of us new to Mac OS X, the sub-directories under there look a little foreign.

To run WLS, you need to set JAVA_HOME to the appropriate directory before you can start a domain.  Hardcoding the directory into either .bashrc or the startWebLogic.sh scripts does the trick.

But today I stumbled on another little utility that can be used to dynamically determine the current  JAVA_HOME, as set in the user preferences:

       java_home - return a value for $JAVA_HOME

       /usr/libexec/java_home [options]

       The  java_home  command  returns  a path suitable for setting the JAVA_HOME environment variable.  It
       determines this path from the user's preferred Java in the Java Preferences application.   Additional
       constraints may be provided to filter the list of JVMs available.  By default, if no constrants match
       the available list of JVMs, the default order is used.  The path is printed to standard output.

Thus setting JAVA_HOME dynamically in scripts, shell profiles can be done simply like this:

export JAVA_HOME=`/usr/libexec/java_home`


robert.nix said...

Just to point out, the benefit to this is because Mac OS X can change the default JDK using the Java Preferences.app and, as new builds are installed via System Update, they can be enabled by default without requiring any manual user intervention while still retaining the ability to manually override the default if and when needed.

It's a little unusual from a java perspective but it's fairly in keeping with how Mac OS tries to maintain reasonable defaults and avoid unneeded manual actions.

Also, just to point out, that's platform specific. I generally prefer to create a link like ~/java/jdk to /System/Library/Frameworks/JavaVM.framework/Home (which should always point to the default JDK) so that i can maintain a common script to set JAVA_HOME regardless of the system.

It's curious to me why your WLS didn't recognize the JAVA_HOME during installation. Maybe i already had my JAVA_HOME configured before installation because it found it when i installed WLS so there was no need to update the installation.

Ewan Benfield said...

Great, was trying to work out why the Java Preferences settings weren't being reflected in Terminal....