Java软引用&弱引用使用示例代码

一、示例代码

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]

五、参考链接

  1. 如何通过软引用和弱引用提升JVM内存使用性能!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值