Tuesday, July 7, 2009

Switching between 64 bit and 32 bit JVMs in Windows

I run Vista 64 bit on my laptop to get at the ludicrous 6Gb of memory that I seem to need to do my work these days. However I find that because of native library dependencies there are often times when I need to switch between 32 and 64 bit JVMs.

To do so I hacked together this simple batch file which allows you to simply switch JAVA_HOME:

xjava.bat:


@echo off
@rem Allow swiching between 64 and 32 bit versions of jvm.

SET OLD_JAVA_HOME=%JAVA_HOME%

@rem Process switch
set XJAVA_SWITCH=%1
shift
if "%XJAVA_SWITCH%" == "" goto DISPLAY_CURRENT
if "%XJAVA_SWITCH%" == "-64" goto SET_64
if "%XJAVA_SWITCH%" == "-32" goto SET_32
goto DISPLAY_JAVA_HOME_AND_CHECK_FOR_CMD_TO_EXEC

:SET_32
if "%JAVA_32_HOME%" == "" goto ERROR_32
set JAVA_HOME=%JAVA_32_HOME%
goto DISPLAY_JAVA_HOME_AND_CHECK_FOR_CMD_TO_EXEC

:ERROR_32
echo Error: JAVA_32_HOME not set.
goto DONE

:SET_64
if "%JAVA_64_HOME%" == "" goto ERROR_64
set JAVA_HOME=%JAVA_64_HOME%
goto DISPLAY_JAVA_HOME_AND_CHECK_FOR_CMD_TO_EXEC

:ERROR_64
echo Error: JAVA_64_HOME not set.
goto DONE

:DISPLAY_CURRENT
@ECHO JAVA_HOME=%JAVA_HOME%
goto DONE

:DISPLAY_JAVA_HOME_AND_CHECK_FOR_CMD_TO_EXEC
@rem Display JAVA_HOME
@ECHO JAVA_HOME=%JAVA_HOME%
if "%JAVA_HOME%" == "%JAVA_32_HOME" echo "Using 32 bit JVM"
if "%JAVA_HOME%" == "%JAVA_64_HOME" echo "Using 64 bit JVM"

@rem Check for java command to execute, otherwise we just set JAVA_HOME
if "%1" == "" goto DONE
set _ARGS=%*
set _ARGS=%_ARGS:-32=%
set _ARGS=%_ARGS:-64=%
"%JAVA_HOME%/bin/java" %_ARGS%
set JAVA_HOME=%OLD_JAVA_HOME%
goto DONE

:DONE



Save as xjava.bat somwhere on your path. You then need to define the environment variables: JAVA_32_HOME and JAVA_64_HOME.

You then use this as follows:

  1. Print the current JAVA_HOME: xjava
  2. Switch to 32 bit VM: xjava -32
  3. Switch to 64 bit VM: xjava -64
  4. Run java with JAVA_HOME set to the appropriate vm: xjava [-32|-64] MyClass