为什么我们需要Java中的弱引用 [英] Why do we need weak reference in java

查看:54
本文介绍了为什么我们需要Java中的弱引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解弱引用是垃圾收集器的摆布,我们不能保证弱引用会存在.我看不到需要引用较弱的内容,但请确定应该有一个理由.

I understand that weak references are at the mercy of the garbage collector, and we cannot guarantee that the weak reference will exist. I could not see a need to have weak reference, but sure there should be a reason.

  • 为什么我们需要在Java中使用弱引用?
  • Java中弱引用的实际(某些)用法是什么?如果您可以分享您在项目中的使用方式,那就太好了!

推荐答案

使用弱哈希表实际上通常是一个坏主意.首先,很容易出错,但更糟糕的是,它通常用于实现某种缓存.

It's actually quite often a bad idea to use weak hashmaps. For one it's easy to get wrong, but even worse it's usually used to implement some kind of cache.

这意味着以下内容:您的程序在一段时间内运行良好且性能良好,在压力下,我们分配了越来越多的内存(更多的请求=更多的内存压力=可能还有更多的缓存条目),这随后导致产生GC.

What this does mean is the following: Your program runs fine with good performance for some time, under stress we allocate more and more memory (more requests = more memory pressure = probably more cache entries) which then leads to a GC.

现在,当系统处于高压力下时,您不仅会获得GC,而且会在最需要时失去整个缓存.这个问题不好玩,因此您至少必须使用大小合理的硬引用LRU缓存来缓解该问题-那时您仍然可以使用weakrefs,但只能作为附加帮助.

Now suddenly while your system is under high stress you not only get the GC, but also lose your whole cache, just when you'd need it the most. Not fun this problem, so you at least have to use a reasonably sized hard referenced LRU cache to mitigate that problem - you can still use the weakrefs then but only as an additional help.

我已经看到一个以上的项目被该"bug"击中..

I've seen more than one project hit by that "bug"..

这篇关于为什么我们需要Java中的弱引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆