我对软/弱引用看了也不少博客,但是还是有一点疑问,尤其是android 2.3
之后的软/弱引用机制
尝试搜索无果后,来这里请教一下,问题应该很简单,但是对我来说很困惑有点绕不过来弯.
谢谢
ViewStub
和其他很多地方都有用到WeakReference
弱引用不是在系统GC的时候如果它只被一个软引用所引用,那么它将会被回收吗?
在ViewStub
的源码中,在inflate()
一个ViewStub
的之后
同时将inflate()
完毕的view
添加至新创建的WeakReference
中,
那么这个view
不就只?
被一个软引用所引用了吗?
如果这时系统GC
那么view是不是被回收了?那么下次想从WeakReference
中获取它的时候是不是又可能会为null
?从而导致错误?
或者说这种情况是不会被系统GC
的? 望大鸟指教一下愚昧小弟
PHPz2017-04-18 09:08:48
I think your understanding of the WeakReference mechanism is correct, but your understanding of the ViewStub code is wrong
WeakReference is used in ViewStub and many other places
Isn’t a weak reference that will be recycled if it is only referenced by a soft reference during system GC?
Will
In the source code of ViewStub, after inflate() a ViewStub,
add the inflate()ed view to the newly created WeakReference.
Isn’t this view just referenced by a soft reference?
The reference relationship of related objects is as follows:
inflate()第一次执行前:
parentView --强-> stubView
此时inflatedView还不存在
inflate()第一次执行后:
parentView --强-> inflatedView
stubView --弱->inflatedView
此时parentView已经不引用stubView了,stubView在inflate()中用inflatedView替换了parentView中的自己
So inflatedView is still strongly referenced and will not be GC