有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

jvm Java中的软引用用例是什么?

Java中软引用的用例是什么?当JVM内存不足时,垃圾收集非关键项是否有用,以便在关闭JVM之前释放足够的资源来转储关键信息

它们被称为软引用,因为它们是软的,在“受到压力”时会中断,即:JVM内存不足。我理解弱引用和幻影引用,但并不真正理解何时需要它们


共 (4) 个答案

  1. # 1 楼答案

    我能想到的最好的例子就是缓存。如果内存出现问题,您可能不介意转储缓存中最旧的条目。缓存大型对象图也可能会导致这种情况

  2. # 2 楼答案

    有关如何将软引用用作缓存的示例,请参见本post

  3. # 3 楼答案

    This article让我很好地理解了它们中的每一个(弱引用、软引用和幻影引用)。这里有一个总结的例子:

    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.

    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.

    A phantom reference is quite different than either SoftReference or WeakReference. Its grip on its object is so tenuous that you can't even retrieve the object -- its get() method always returns null. The only use for such a reference is keeping track of when it gets enqueued into a ReferenceQueue, as at that point you know the object to which it pointed is dead.

  4. # 4 楼答案

    一个用途是缓存。假设您希望维护大型对象的内存缓存,但不希望该缓存占用可用于其他目的的内存(因为缓存始终可以重建)。通过维护对对象的软引用缓存,JVM可以释放被引用的对象,并将它们占用的内存重新用于其他目的。缓存只需要在遇到断开的软引用时清除它们

    另一用途可用于在存储器受限的设备(例如移动电话)上维护应用程序图像。当用户打开应用程序时,可以将以前的应用程序映像作为软引用进行维护,以便在其他内容需要内存时将其清除,但在不需要内存时仍将保留。这将允许用户在没有内存压力的情况下更快地返回到应用程序,并允许在需要其他内容时回收以前应用程序的内存