Quick note: WeakReference
2013-12-12 14:30 xiao蜗牛 阅读(278) 评论(0) 编辑 收藏 举报1 The usage of WeakReference
Grammar: WeakReference<ClassA> weakA = new WeakReference<ClassA>(instanceOfA);
Scene: Weak references are useful for mappings that should have their entries removed automatically once they are not referenced any more (from outside).
在map中弱引用是有用的,当外部不再引用时,它的条目会被自动移除。(为什么呢???)
Reference: http://developer.android.com/reference/java/lang/ref/WeakReference.html
2 WeakReference & garbage collection
Once the garbage collector decides that an object obj
is is weakly-reachable, the following happens:
- A set
ref
of references is determined.ref
contains the following elements:- All weak references pointing to
obj
. - All weak references pointing to objects from which
obj
is either strongly or softly reachable.
- All weak references pointing to
- All references in
ref
are atomically cleared. - All objects formerly being referenced by
ref
become eligible for finalization. - At some future point, all references in
ref
will be enqueued with their corresponding reference queues, if any.
一旦垃圾收集器决定一个obj是弱可及的,将会发生下面的事情:
1)一系列引用的ref被决定。ref包含:
a) 所有指向obj的弱引用。b) 所有指向obj的强可及或弱可及对象的弱引用。
2)ref中的所有引用被自动清除。
3)ref中此前被引用的对象在finalization阶段(我的理解是finialize方法执行时)被选定。
4)在未来的某个时刻,在ref中的所有引用将被加入到它们对应的引用队列中,如果队列存在的话。(加入以后呢???)
3 WeakReference vs. SoftReference
The difference between a SoftReference
and a WeakReference
is the point of time at which the decision is made to clear and enqueue the reference:
- A
SoftReference
should be cleared and enqueued as late as possible, that is, in case the VM is in danger of running out of memory. - A
WeakReference
may be cleared and enqueued as soon as is known to be weakly-referenced.
区别在于清除和进队的时机:
a)软引用会被尽量晚的清除和进队,比如在VM内存将要耗尽的时候。
b)弱引用可能会在确定为弱引用时被清除和进队。