问题:运行java应用,出现java.lang.OutOfMemoryError: Java heap space,即使在环境变量里设置了JAVA_OPTS -Xmx2048m还是报错。
分析及解决:
1.JAVA_OPTS只对tomcat/weblogic等Web服务器中间件有效,以“java -cp [*.jar] test.Main”方式运行的不会去读取JAVA_OPTS.
2.如果在运行java类,需要设置Heap Size的话,需要如下方式:
java -Xmx2048m -jar zoio.jar或者java -Xmx1024m -cp zoio.jar info.zoio.Main
3.如果是在Unix或者Aix服务器上,可以直接写下如下语句
export JAVA_OPTS=-Xmx1024m -Djava.awt.headless=true
java $JAVA_OPTS -cp zoio.jar info.zoio.Main
或者vi test.sh文件,写下:
#!/bin/sh
classpath=./zoio.jar
/usr/java6/bin/java -Xmx1024M -cp $classpath info.zoio.Main
4.对于非Java语言(C++)调用Java代码,最好的方式是提供给操作员设置的页面,再申明JavaVM时,将JavaOPTS数值放置至JavaVM中。
对于JVM设置,可以查考如下配置example:
# Memory configuration
JAVA_OPTS="-server"
JAVA_OPTS="$JAVA_OPTS -Xms1280m"
JAVA_OPTS="$JAVA_OPTS -Xmx1280m"
JAVA_OPTS="$JAVA_OPTS -XX:NewSize=640m"
JAVA_OPTS="$JAVA_OPTS -XX:MaxNewSize=640m"
JAVA_OPTS="$JAVA_OPTS -XX:SurvivorRatio=5"
JAVA_OPTS="$JAVA_OPTS -XX:TargetSurvivorRatio=90"
JAVA_OPTS="$JAVA_OPTS -XX:MaxTenuringThreshold=12"
JAVA_OPTS="$JAVA_OPTS -XX:+UseConcMarkSweepGC"
JAVA_OPTS="$JAVA_OPTS -XX:+CMSIncrementalMode"
JAVA_OPTS="$JAVA_OPTS -XX:+CMSIncrementalPacing"
JAVA_OPTS="$JAVA_OPTS -XX:+CMSParallelRemarkEnabled"
JAVA_OPTS="$JAVA_OPTS -XX:+UseParNewGC"
JAVA_OPTS="$JAVA_OPTS -XX:PermSize=64m"
JAVA_OPTS="$JAVA_OPTS -XX:MaxPermSize=64m"
JAVA_OPTS="$JAVA_OPTS -XX:+UseTLAB"
# Enable class unloading (needed with ConcMarkSweepGC)
JAVA_OPTS="$JAVA_OPTS -XX:+CMSClassUnloadingEnabled"
JAVA_OPTS="$JAVA_OPTS -XX:+CMSPermGenSweepingEnabled"
# debug and memory tweaks to avoid Hotspot Compiler Failure
JAVA_OPTS="$JAVA_OPTS -XX:+PrintCompilation"
JAVA_OPTS="$JAVA_OPTS -XX:CodeCacheMinimumFreeSpace=2M"
JAVA_OPTS="$JAVA_OPTS -XX:ReservedCodeCacheSize=64M"
JAVA_OPTS="$JAVA_OPTS -XX:CompileCommandFile=/my/portal/bin/hotspot_compiler"
# Enable JMX Remote Monitoring
JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote"
JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.port=9000"
JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.ssl=false"
JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.password.file=/my/portal/bin/jmxremote.password"
JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.access.file=/my/portal/bin/jmxremote.access"
# turn on some debug for GC only print the distribution when doing tuning
JAVA_OPTS="$JAVA_OPTS -verbose:gc"
JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCTimeStamps"
JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCDetails"
#JAVA_OPTS="$JAVA_OPTS -XX:+PrintTenuringDistribution"
JAVA_OPTS="$JAVA_OPTS -Xloggc:/my/portal/logs/portal/gc.log"
# Enable remote debugging port
JAVA_OPTS="$JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"