java.lang.ref.WeakReference和java.lang.ref.SoftReference有什么区别?


当前回答

弱引用 http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ref/WeakReference.html

原理:弱引用与垃圾回收相关。通常,具有一个或多个引用的对象将不符合垃圾收集的条件。 上述原则在弱参考时不适用。如果一个对象对其他对象只有弱引用,那么它就可以进行垃圾收集了。

让我们看看下面的例子:我们有一个Map with Objects,其中Key是引用一个对象。

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());

    }
}

现在,在程序执行期间,我们使emp = null。持有键的Map在这里没有意义,因为它是空的。在上述情况下,对象不会被垃圾收集。

WeakHashMap

在WeakHashMap中,当不再可能从Map中检索条目时,条目(键到值的映射)将被删除。

让我用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());
    }
}

输出:对System.gc()进行了20次调用,导致高德地图大小为:0。

WeakHashMap只有对键的弱引用,没有像其他Map类那样的强引用。虽然使用了WeakHashMap,但在某些情况下,当值或键被强引用时,您必须小心。这可以通过将对象包装在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");
    }
}

软引用。

软引用比弱引用强一些。软引用允许垃圾回收,但只有在没有其他选择时才请求垃圾回收器清除它。

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.

其他回答

弱引用 http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ref/WeakReference.html

原理:弱引用与垃圾回收相关。通常,具有一个或多个引用的对象将不符合垃圾收集的条件。 上述原则在弱参考时不适用。如果一个对象对其他对象只有弱引用,那么它就可以进行垃圾收集了。

让我们看看下面的例子:我们有一个Map with Objects,其中Key是引用一个对象。

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());

    }
}

现在,在程序执行期间,我们使emp = null。持有键的Map在这里没有意义,因为它是空的。在上述情况下,对象不会被垃圾收集。

WeakHashMap

在WeakHashMap中,当不再可能从Map中检索条目时,条目(键到值的映射)将被删除。

让我用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());
    }
}

输出:对System.gc()进行了20次调用,导致高德地图大小为:0。

WeakHashMap只有对键的弱引用,没有像其他Map类那样的强引用。虽然使用了WeakHashMap,但在某些情况下,当值或键被强引用时,您必须小心。这可以通过将对象包装在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");
    }
}

软引用。

软引用比弱引用强一些。软引用允许垃圾回收,但只有在没有其他选择时才请求垃圾回收器清除它。

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.

这篇文章对于理解强引用、软引用、弱引用和幻影引用非常有帮助。


总结一下,

如果对一个对象只有弱引用(没有强引用),那么该对象将在下一个GC循环中被GC回收。

如果对对象只有软引用(没有强引用),那么只有当JVM内存耗尽时,GC才会回收该对象。


所以你可以说,强引用具有强大的功能(GC永远不会收集)。

软引用比弱引用更强大(因为它们可以逃避GC循环,直到JVM耗尽内存)

弱引用甚至不如软引用强大(因为它们不能逃避任何GC循环,如果对象没有其他强引用,就会被回收)。


餐厅的类比

服务员- GC 堆中的对象 餐厅区域/空间-堆空间 新客户-在餐厅想要桌子的新对象

现在,如果您是一个强客户(类似于强引用),那么即使餐厅里来了一个新客户或发生了其他事情,您也不会离开您的表(堆上的内存区域)。服务员没有权利告诉你(甚至要求你)离开餐厅。

如果你是一个软顾客(类似于软参考),那么如果餐厅来了一个新顾客,服务员不会让你离开桌子,除非没有其他空桌子来容纳新顾客。(换句话说,只有当一个新顾客进来,并且没有其他的桌子给这个新顾客时,服务员才会叫你离开桌子)

如果你是一个弱顾客(类似于弱参考),那么服务员可以根据他的意愿(在任何时候)要求你离开餐厅:P

Java中的六种对象可达性状态:

Strongly reachable objects - GC will not collect (reclaim the memory occupied by) this kind of object. These are reachable via a root node or another strongly reachable object (i.e. via local variables, class variables, instance variables, etc.) Softly reachable objects - GC may attempt to collect this kind of object depending on memory contention. These are reachable from the root via one or more soft reference objects Weakly reachable objects - GC must collect this kind of object. These are reachable from the root via one or more weak reference objects Resurrect-able objects - GC is already in the process of collecting these objects. But they may go back to one of the states - Strong/Soft/Weak by the execution of some finalizer Phantomly reachable object - GC is already in the process of collecting these objects and has determined to not be resurrect-able by any finalizer (if it declares a finalize() method itself, then its finalizer will have been run). These are reachable from the root via one or more phantom reference objects Unreachable object - An object is neither strongly, softly, weakly, nor phantom reachable, and is not resurrectable. These objects are ready for reclamation

欲了解更多详细信息:https://www.artima.com/insidejvm/ed2/gc16.html«崩溃

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.

另一方面,softreference对于缓存外部的、可重新创建的资源很有好处 因为GC通常会延迟清除它们。尽管如此,这是有保证的 在抛出OutOfMemoryError之前,sofreferferences将被清除 理论上不会引起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.

现在是[*]。保持一个SoftReference本身不会导致OOME。如果 另一方面,你错误地把软参考用在了一个弱参考的任务上 (也就是说,你以某种方式保存与对象相关的信息 ,并在Reference对象获得时丢弃它 清除),您可以运行OOME作为您的代码轮询referencqueuue 而丢弃关联对象可能会发生不及时运行的情况 时尚。

所以,决定取决于使用情况 -如果你缓存的信息构造起来很昂贵,但是 尽管如此,可从其他数据重构,使用软引用 -如果您保留对某些数据的规范实例的引用,或者 您希望拥有对对象的引用,但不“拥有”它(因此 防止它被GC),使用弱引用。

应该注意,弱引用对象只有在只有弱引用时才会被收集。如果它有一个强引用,那么无论它有多少弱引用,它都不会被收集。