Using Java's ReferenceQueue

前端 未结 4 1596
轮回少年
轮回少年 2020-12-01 00:23

Do SoftReference and WeakReference really only help when created as instance variables? Is there any benefit to using them in method scope?

4条回答
  •  独厮守ぢ
    2020-12-01 01:08

    If an object has only WeakReferences (or no references whatsoever!) towards it, it can be garbage collected whenever Java needs to make more room in memory. So, you use WeakReferences whenever you want an object to remain in memory, but you don't need it to remain THAT badly (e.g. if Java needs to garbage collect it, no problem, you can get it back somehow and in the mean time Java has better performance)

    Enqueuing a WeakReference allows you to iterate the ReferenceQueue and determine which references have been garbage collected and which have not. That's all - so only do it if you need to know this.

    Read more: http://weblogs.java.net/blog/2006/05/04/understanding-weak-references

提交回复
热议问题