Fix Javac java lang OutOfMemoryError

When javac is compiling a large number of java source files, it may fail with java.lang.OutOfMemoryError:
The system is out of resources.
Consult the following stack trace for details.
java.lang.OutOfMemoryError: Java heap space
It's no different than OutOfMemoryError in other java applications. When you run javac in Sun JDK, it's invoking com.sun.tools.javac.main.Main located in %JAVA_HOME%\lib\tools.jar.

If you are compiling with javac task in Apache Ant, set fork attribute to true, to run javac in a separate process with its own heap size settings. If fork is set to false, or not set (default is false), javac will run in the same process as Ant, which has a default maximum heap size of 64m. The following is a snippet from build.xml:
<javac fork="true"
srcdir="${basedir}/src"
destdir="${basedir}/build/classes"
classpath="${project.classpath}"
includeantruntime="false"
memoryinitialsize="256m"
memorymaximumsize="256m">
<compilerarg line="-endorseddirs ${env.CATALINA_BASE}/endorsed" />
</javac>
Setting fork to true will also limit any memory leaks in javac implementation to its own child process, without affecting the parent Ant process.

If setting fork, memoryInitialSize, and memoryMaximumSize still doesn't fix the problem, you can execute javac task several times, each javac compiling a subset of your source tree. But this should really be the last rescort, since you are now managing source code dependency, which should be javac's business. You will need to decide which modules get compiled first, and classes in certain modules cannot have direct references to classes in certain other modules, and so on. I'd rather increase the memoryMaximumSize to 2g.

If you don't want to modify existing build.xml files, another option is to increase the heap size for Ant JVM and still execute javac task in-process. You just need to set environment variable ANT_OPTS:
export ANT_OPTS="-Xms256m -Xmx256m"    (ksh/bash)
setenv ANT_OPTS="-Xms256m -Xmx256m" (tcsh/csh)
set ANT_OPTS=-Xms256m -Xmx256m (Windows)
A disadvantage of this approach is users will need to remember to set this environment variable, or use some sort of wrapper script on top of %ANT_HOME%\bin\ant.bat, or $ANT_HOME/bin/ant.

If you are invoking javac directly, you can also increase the heap size for the underlying JVM:
javac -d build/classes -classpath ... -J-Xms256m -J-Xmx256m java-source-files

Followers

Pageviews Last 7 Days