通过gc和linux脚本监控内存,防止内存溢出(java.lang.OutOfMemoryErr)

现象:程序抛出java.lang.OutOfMemoryError.

解决办法:在java启动项中加入

-Xms1800M -Xmx1800M -Xmn600M -Xss512K -XX:PermSize=300M -XX:MaxPermSize=300M -XX:SurvivorRatio=5000 -XX:MaxTenuringThreshold=0 -Xnoclassgc -XX:+DisableExplicitGC -XX:+UseParNewGC -XX:+PrintClassHistogram -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintHeapAtGC -Xloggc:/usr/local/apache/htdocs/SoapMmsService/logs/gc.log



内存参数大小可以根据服务器自己设置.
当eden space的内存占用达到99%以上,进行gc.

Heap
par new generation total 614336K, used 614259K [0x44920000, 0x6a120000, 0x6a120000)
eden space 614272K, 99% used [0x44920000, 0x6a0fccc0, 0x6a100000)
from space 64K, 0% used [0x6a100000, 0x6a100000, 0x6a110000)
to space 64K, 0% used [0x6a110000, 0x6a110000, 0x6a120000)
tenured generation total 1228800K, used 0K [0x6a120000, 0xb5120000, 0xb5120000)
the space 1228800K, 0% used [0x6a120000, 0x6a120000, 0x6a120200, 0xb5120000)
compacting perm gen total 307200K, used 4372K [0xb5120000, 0xc7d20000, 0xc7d20000)
the space 307200K, 1% used [0xb5120000, 0xb55650c8, 0xb5565200, 0xc7d20000)
0.000: [ParNew: 614259K->0K(614336K), 0.3373210 secs] 614259K->25531K(1843136K) Heap after GC invocations=1:


gc完成后


Heap
par new generation total 614336K, used 0K [0x44920000, 0x6a120000, 0x6a120000)
eden space 614272K, 0% used [0x44920000, 0x44920000, 0x6a100000)
from space 64K, 0% used [0x6a110000, 0x6a110000, 0x6a120000)
to space 64K, 0% used [0x6a100000, 0x6a100000, 0x6a110000)
tenured generation total 1228800K, used 25531K [0x6a120000, 0xb5120000, 0xb5120000)
the space 1228800K, 2% used [0x6a120000, 0x6ba0ee10, 0x6ba0f000, 0xb5120000)
compacting perm gen total 307200K, used 4372K [0xb5120000, 0xc7d20000, 0xc7d20000)
the space 307200K, 1% used [0xb5120000, 0xb55650c8, 0xb5565200, 0xc7d20000)
} , 0.3374670 secs]
1060.498: [GC {Heap before GC invocations=1:

启动一段时间,服务器进行gc时.在gc.log日志中会出现gc日志.

当日志中的eden space进行gc完成后不能归0.而是不断增长的趋势.当最后gc完成仍然和gc前大小一样时,就会出现java.lang.OutOfMemoryError.

使用sh脚本来监控gc日志


cd /usr/local/apache/htdocs/SoapMmsService/logs
more gc.log | grep "eden space" > test.log
content=`sed -n '$'p test.log`
percent=`sed -n '$'p test.log | awk '{print $4}' | awk -F% '{print $1}'`
echo $percent
base=0
echo $base
maxcount=98
if test $percent -gt $base; then
if test $percent -lt $maxcount; then
echo "test"
wget "http://127.0.0.1:6666/control" >tmp
fi
fi


当gc中的日志出现异常.通知一个web接口.这个接口目前可以利用公司资源可以用短信做提示.如果没有这个,可以这里实现重启之类的操作.

你可能感兴趣的:(程序文章)