一、示例代码
public class ReferencesObjs {
static class M2Object {
byte[] m2 = new byte[2 * 1024 * 1024];
}
public static void main(String[] args) throws Exception {
M2Object o = new M2Object();
SoftReference<M2Object> s = new SoftReference<ReferencesObjs.M2Object>(o);
o = null;
System.gc();
Thread.sleep(100);
System.out.println(s.get() == null);
o = new M2Object();
WeakReference<M2Object> m = new WeakReference<ReferencesObjs.M2Object>(o);
o = null;
System.gc();
Thread.sleep(100);
System.out.println(m.get() == null);
System.out.println(s.get() == null);
}
}
二、JVM参数
-Xmx5M -Xloggc:gc.log
三、输出
false
true
true
四、gc.log日志
Java HotSpot(TM) Client VM (25.111-b14) for windows-x86 JRE (1.8.0_111-b14), built on Sep 22 2016 18:54:33 by "java_re" with MS VC++ 10.0 (VS2010)
Memory: 4k page, physical 12463344k(4247680k free), swap 24924828k(14339656k free)
CommandLine flags: -XX:InitialHeapSize=5242880 -XX:MaxHeapSize=5242880 -XX:+PrintGC -XX:+PrintGCTimeStamps -XX:-UseLargePagesIndividualAllocation
0.225: [Full GC (System.gc()) 3083K->2699K(5952K), 0.0023907 secs]
0.328: [GC (Allocation Failure) 2732K->2699K(5952K), 0.0001911 secs]
0.328: [Full GC (Allocation Failure) 2699K->2699K(5952K), 0.0014690 secs]
0.330: [Full GC (Allocation Failure) 2699K->640K(5952K), 0.0014604 secs]
0.332: [Full GC (System.gc()) 2721K->640K(5952K), 0.0016531 secs]