`

Difference between a soft reference and a weak reference in Java

 
阅读更多

From Understanding Weak References, by Ethan Nicholas:

Weak references

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 Widgetobject. 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

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.

And Peter Kessler added in a comment:

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.

Weak references are collected eagerly. If GC finds that an object is weakly reachable (reachable only through weak references), it'll clear the weak references to that object immediately. As such, they're good for keeping a reference to an object for which your program also keeps (strongly referenced) "associated information" somewere, like cached reflection information about a class, or a wrapper for an object, etc. Anything that makes no sense to keep after the object it is associated with is GC-ed. When the weak reference gets cleared, it gets enqueued in a reference queue that your code polls somewhere, and it discards the associated objects as well. That is, you keep extra information about an object, but that information is not needed once the object it refers to goes away. Actually, in certain situations you can even subclass WeakReference and keep the associated extra information about the object in the fields of the WeakReference subclass. Another typical use of WeakReference is in conjunction with Maps for keeping canonical instances.

SoftReferences on the other hand are good for caching external, recreatable resources as the GC typically delays clearing them. It is guaranteed though that all SoftReferences will get cleared before OutOfMemoryError is thrown, so they theoretically can't cause an OOME[*].

Typical use case example is keeping a parsed form of a contents from a file. You'd implement a system where you'd load a file, parse it, and keep a SoftReference to the root object of the parsed representation. Next time you need the file, you'll try to retrieve it through the SoftReference. If you can retrieve it, you spared yourself another load/parse, and if the GC cleared it in the meantime, you reload it. That way, you utilize free memory for performance optimization, but don't risk an OOME.

Now for the [*]. Keeping a SoftReference can't cause an OOME in itself. If on the other hand you mistakenly use SoftReference for a task a WeakReference is meant to be used (namely, you keep information associated with an Object somehow strongly referenced, and discard it when the Reference object gets cleared), you can run into OOME as your code that polls the ReferenceQueue and discards the associated objects might happen to not run in a timely fashion.

So, the decision depends on usage - if you're caching information that is expensive to construct, but nonetheless reconstructible from other data, use soft references - if you're keeping a reference to a canonical instance of some data, or you want to have a reference to an object without "owning" it (thus preventing it from being GC'd), use a weak reference.

 

The only real difference between a soft reference and a weak reference is that the garbage collector uses algorithms to decide whether or not to reclaim a softly reachable object, but always reclaims a weakly reachable object.

 

Weak Reference http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ref/WeakReference.html

weak reference is related to garbage collection. Normally, object having one or more referencewill not be eligible for garbage collection. Thea above rule is not applicable when it is weak reference. It an object has only weak reference with other objects, then its ready for garbage collection.

Let's now look at the below example. We have an Map with Objects where Key is Some Class Reference object.

import java.util.HashMap;   
public class Test {
    public static void main(String args[]) {
        HashMap<Employee, EmployeeVal> aMap = new 
                       HashMap<Employee, EmployeeVal>();

        Employee emp = new Employee("Vinoth");
        EmployeeVal val = new EmployeeVal("Programmer");

        aMap.put(emp, val);

        emp = null;

        System.gc();
        System.out.println("Size of Map" + aMap.size());
    }
}

 

Now, during the execution of the program we have made emp = null. The Map holding the the key makes no sense here as the it is null. In the above situaton, the object is not garbage collected.

WeakHashMap

WeakHashMap is one where the entries (key-to-value mappings) will be removed when it is no longer possible to retrieve them from the map.

Let me show the above example same with WeakHashMap

import java.util.WeakHashMap;

public class Test {

    public static void main(String args[]) {
        WeakHashMap<Employee, EmployeeVal> aMap = 
                    new WeakHashMap<Employee, EmployeeVal>();

        Employee emp = new Employee("Vinoth");
        EmployeeVal val = new EmployeeVal("Programmer");

        aMap.put(emp, val);

        emp = null;

        System.gc();
        int count = 0;
        while (0 != aMap.size()) {
            ++count;
            System.gc();
        }
        System.out.println("Took " + count
                + " calls to System.gc() to result in weakHashMap size of : "
                + aMap.size());
    }
}

 

Took 20 calls to System.gc() to result in aMap size of : 0.

WeakHashMap has only weak references to the keys, not strong references like other Map classes. There are situations which you have to take care when the value or key is strongly referenced though you have used WeakHashMap. This can avoided by wrapping the object in a WeakReference.

import java.lang.ref.WeakReference;
import java.util.HashMap;

public class Test {

    public static void main(String args[]) {
        HashMap<Employee, EmployeeVal> map = 
                      new HashMap<Employee, EmployeeVal>();
        WeakReference<HashMap<Employee, EmployeeVal>> aMap = 
                       new WeakReference<HashMap<Employee, EmployeeVal>>(
                map);

        map = null;

        while (null != aMap.get()) {
            aMap.get().put(new Employee("Vinoth"),
                    new EmployeeVal("Programmer"));
            System.out.println("Size of aMap " + aMap.get().size());
            System.gc();
        }
        System.out.println("Its garbage collected");
    }
}

 

Soft References.

Soft Reference is slightly stronger that weak reference. Soft reference allows for garbage collection, but begs the garbage collector to clear it only if there is no other option.

The garbage collector does not aggressively collect softly reachable objects the way it does with weakly reachable ones -- instead it only collects softly reachable objects if it really "needs" the memory. Soft references are a way of saying to the garbage collector, "As long as memory isn't too tight, I'd like to keep this object around. But if memory gets really tight, go ahead and collect it and I'll deal with that." The garbage collector is required to clear all soft references before it can throw OutOfMemoryError.

 

Reference:

http://stackoverflow.com/questions/299659/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java

 

分享到:
评论

相关推荐

    Java功底之Reference

    在Java编程语言中,`Reference`类是一个非常特殊且重要的概念,它超出了常规的引用类型,如`Object`或数组引用。`Reference`类及其子类主要用于处理对象的软引用、弱引用和虚引用,这些引用类型在内存管理,特别是...

    java7帮助文档

    see Appendix D: Disabling Cryptographic Algorithms in Java PKI Programmer's Guide and Disabled Cryptographic Algorithms in Java Secure Socket Extension (JSSE) Reference Guide. Various enhancements ...

    C++ Standard Library The A Tutorial and Reference 英文版

    《C++ Standard Library The A Tutorial and Reference》是一本详尽且深入的C++标准库教程与参考手册,专为那些希望深入理解并充分利用C++标准库的开发者设计。这本书覆盖了C++语言的核心库,包括容器、算法、迭代器...

    GObject Reference Manual

    Signals - A means for customization of object behaviour and a general purpose notification mechanism Closures - Functions as first-class objects Value arrays - A container structure to maintain an ...

    A Basic Course in Probability Theory

    The authors assume a graduate level of maturity in mathematics, but otherwise the book will be suitable for students with varying levels of background in analysis and measure theory. In particular, ...

    1Z0-811 Exam Guide to Have a Cakewalk in Oracle Java SE Certific

    - **Arrays and Collections:** Study the handling of arrays and collections in Java. - **Exception Handling:** Understand exception handling mechanisms in Java. - **File Handling:** Learn about file...

    Java学习之Reference、Eclipse调优、jvisualvm使用

    通常,Java有四种类型的引用:强引用(Strong Reference)、软引用(Soft Reference)、弱引用(Weak Reference)和虚引用(Phantom Reference)。强引用是最常见的类型,当对象被强引用持有时,垃圾回收器不会回收...

    SSD7 选择题。Multiple-Choice

    (c) typing a syntactically correct SQL query that uses column and table names similar to the correct column and table names in a database (d) writing an English description of the data that the user...

    Weak Convergence and Empirical Processes

    弱收敛余经验过程是概率统计专业博士生的必修课程,也是经典书籍。

    Java中的引用类型详解:强引用、软引用、弱引用与虚引用

    从JDK 1.2版本开始,Java引入了四种不同级别的引用:强引用(Strong Reference)、软引用(Soft Reference)、弱引用(Weak Reference)和虚引用(Phantom Reference)。这些引用类型提供了灵活的内存管理策略,允许...

    C++ Standard Library -- A Tutorial and Reference

    《C++ Standard Library -- A Tutorial and Reference》是C++编程领域的一部权威之作,由Alexandrescu和Sutter合著,旨在为开发者提供全面、深入的C++标准库使用指南。这本书不仅适合初学者系统学习,也适合作为经验...

    On super weak compactness of subsets and its equivalences in Banach spaces

    关于Banach空间中的超弱紧子集和其等价性,程立新,程庆进,类比于Banach空间中的弱紧集和超自反空间中子集的性质,本文目的是讨论Banach空间中凸和非凸子集的超弱紧性质。作为结果,本文给出了超�

    Springer-Modern.Multivariate.Statistical.Techniques.Regression.classification.and.manifold.learning.(2008)

    13. **Bagging, Boosting, and Random Forests**: Ensemble methods that combine multiple weak learners to form a strong learner. They are particularly effective in improving predictive accuracy and ...

    Java 中 Reference用法详解

    Java 中 Reference 用法详解 Java 中的 Reference 类型主要分为四种:强引用、软引用、弱引用和虚引用。这些引用类型在 Java 中的使用非常广泛,特别是在缓存、池化和垃圾回收机制中。 强引用(Strong Reference)...

    strong-soft-weak:各种Java参考的示例

    本教程将深入探讨Java中的“强引用”(Strong Reference)、“软引用”(Soft Reference)、“弱引用”(Weak Reference)以及“幻影引用”(Phantom Reference)。这些引用类型在特定场景下能帮助开发者更精细地...

    Iron-Clad Java_Building Secure Web Applications-McGraw Hill(2015).epub

    A product with little security design consideration and a weak security posture discloses few, if any, outward signs of being insecure. Software security, like performance and scalability, cannot be ...

    从面试题中看java的Reference(引用)

    2. 软引用(Soft Reference): 软引用用于实现内存敏感的缓存。软引用的对象在内存不足时会被回收,但会比弱引用对象稍晚一些。当系统内存不足以分配新对象时,垃圾收集器会清除所有软引用的对象。软引用通常与...

    Weak Gravity Conjecture and Holographic/Agegraphic Dark Energy

    弱引力假设(Weak Gravity Conjecture, WGC)是弦理论中的一个重要概念,它提供了一种判别弦理论中半经典一致真空(Landscape)与不一致真空(Swampland)的标准。弱引力假设的基本思想可以简单理解为,在任何一致的...

Global site tag (gtag.js) - Google Analytics