一,概要
通过GC的LOG也能为判断内存泄漏提供些相关信息。
二,例子说明
写一个有泄漏的程序。
package net.dncsoft; import java.util.ArrayList; import java.util.List; public class MainGCTest { public static void main(String[] args) throws Exception { byte[] buf = null; List<byte[]> bufList = new ArrayList<byte[]>(); long counter = 0; while (true) { buf = new byte[1024 * 1024]; bufList.add(buf); Thread.sleep(1000); System.out.println(counter++); } } }
三,运行下面的命令。
java -Xmx16m -Xms16m -XX:NewSize=4m -XX:MaxNewSize=4m -Xloggc:./gc.txt -XX:+PrintGCDetails net.dncsoft.MainGCTest
四,得到这个GCLog文件。
2.119: [GC 2.119: [DefNew: 2314K->148K(3712K), 0.0046925 secs] 2314K->2196K(16000K), 0.0047737 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 5.127: [GC 5.127: [DefNew: 3258K->148K(3712K), 0.0049901 secs] 5306K->5268K(16000K), 0.0050748 secs] [Times: user=0.00 sys=0.01, real=0.02 secs] 8.135: [GC 8.135: [DefNew: 3245K->148K(3712K), 0.0050552 secs] 8365K->8340K(16000K), 0.0051423 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 11.144: [GC 11.144: [DefNew: 3236K->148K(3712K), 0.0054953 secs] 11429K->11413K(16000K), 0.0055777 secs] [Times: user=0.00 sys=0.02, real=0.02 secs] 14.152: [GC 14.152: [DefNew: 3231K->3231K(3712K), 0.0000191 secs]14.153: [Tenured: 11264K->11264K(12288K), 0.0180049 secs] 14495K->14485K(16000K), [Perm : 291K->291K(12288K)], 0.0181553 secs] [Times: user=0.02 sys=0.00, real=0.01 secs] 14.171: [Full GC 14.171: [Tenured: 11264K->11264K(12288K), 0.0124251 secs] 14485K->14471K(16000K), [Perm : 291K->286K(12288K)], 0.0125105 secs] [Times: user=0.01 sys=0.00, real=0.02 secs] Heap def new generation total 3712K, used 3280K [0x319e0000, 0x31de0000, 0x31de0000) eden space 3328K, 98% used [0x319e0000, 0x31d14358, 0x31d20000) from space 384K, 0% used [0x31d20000, 0x31d20000, 0x31d80000) to space 384K, 0% used [0x31d80000, 0x31d80000, 0x31de0000) tenured generation total 12288K, used 11264K [0x31de0000, 0x329e0000, 0x329e0000) the space 12288K, 91% used [0x31de0000, 0x328e00b0, 0x328e0200, 0x329e0000) compacting perm gen total 12288K, used 286K [0x329e0000, 0x335e0000, 0x369e0000) the space 12288K, 2% used [0x329e0000, 0x32a279d0, 0x32a27a00, 0x335e0000) ro space 10240K, 51% used [0x369e0000, 0x36f0baf8, 0x36f0bc00, 0x373e0000) rw space 12288K, 54% used [0x373e0000, 0x37a776d8, 0x37a77800, 0x37fe0000)