java - Java中的SoftReference和WeakReference有什么区别?

标签 java reference weak-references soft-references

最佳答案

来自 Understanding Weak References ,由伊桑·尼古拉斯:

Weak references

A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself. You create a weak reference like this:

WeakReference weakWidget = new WeakReference(widget);

and then elsewhere in the code you can use weakWidget.get() to get the actual Widget object. Of course the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null.

...

Soft references

A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are WeakReferences) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.

SoftReferences aren't required to behave any differently than WeakReferences, but in practice softly reachable objects are generally retained as long as memory is in plentiful supply. This makes them an excellent foundation for a cache, such as the image cache described above, since you can let the garbage collector worry about both how reachable the objects are (a strongly reachable object will never be removed from the cache) and how badly it needs the memory they are consuming.

Peter Kessler 在评论中补充道:

The Sun JRE does treat SoftReferences differently from WeakReferences. We attempt to hold on to object referenced by a SoftReference if there isn't pressure on the available memory. One detail: the policy for the "-client" and "-server" JRE's are different: the -client JRE tries to keep your footprint small by preferring to clear SoftReferences rather than expand the heap, whereas the -server JRE tries to keep your performance high by preferring to expand the heap (if possible) rather than clear SoftReferences. One size does not fit all.

关于java - Java中的SoftReference和WeakReference有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/299659/

相关文章:

java - Spring Batch 电子邮件监听器

C++ 构造函数初始化

c++ - 引用类型和继承问题

java - 有没有办法测试何时从弱集中删除元素?

java - 通过 JSON 和 PHP 发送电子邮件后出现 NullpointerException

java - 按 Ctrl+A 正在更改 JTextPane 中的字体

vector - 为什么在迭代引用向量时会得到对类型的双重引用?

ios - UIView拥有很强的引用性

swift - 如何在类型化为协议(protocol)的 Swift 通用数据结构中使用弱引用?

java.lang.UnsupportedOperationException : JBAS011859: Naming context is read-only 异常