测试一个问题,主动调用GC回收弱引用对象, 结果发现弱引用对象没有被回收.
StudentWh student = new StudentWh();
//用弱引用保存student对象
WeakReference mContextRef = new WeakReference<>(student);
//GC回收前---打印对象
Log.d("111","前mContextRef---" + mContextRef.get());
//主动调用GC回收
System.gc();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//GC回收后---打印对象
Log.d("111","后mContextRef---" + mContextRef.get());
D/111: 前mContextRef---com.roxmotor.basecomponent.toast.StudentWh@be3e8b3
D/111: 后mContextRef---com.roxmotor.basecomponent.toast.StudentWh@be3e8b3
实际操作发现,GC回收前后两次打印结果相同,证明弱引用对象并没有被回收.
哪位码农能解释一下,这是什么原因!
这里你犯了2个错误
1.mContextRef 是个强引用啊,new了一个实例放在mContextRef 里面,如果它被回收了你没有其他引用指向它了,那后续使用不出错了
2.调用gc只是通知gc可以回收了,到底什么时候回收还是gc说了算,它是异步的不是同步的。如果你真的同步等gc回收完毕,那会造成只要调用gc就不知道要卡多长时间(因为你没法确定到底有多少内存需要清理)