相关疑难解决方法(0)

弱参考 - 它们有多大用处?

所以我最近一直在考虑一些自动内存管理的想法 - 具体来说,我一直在寻找基于引用计数实现内存管理器.当然,每个人都知道循环引用会杀死天真的引用计数.解决方案:弱引用.就个人而言,我讨厌以这种方式使用弱引用(还有其他更直观的方法来解决这个问题,通过循环检测),但它让我思考:弱引用还有什么用处?

我认为它们必然存在某种原因,特别是在具有跟踪垃圾收集的语言中,它们不会受到循环参考陷阱的影响(C#和Java是我熟悉的,Java甚至有三种弱引用!).但是,当我试图为他们找到一些可靠的用例时,我几乎只有像"使用它们来实现缓存"这样的想法(我已经在SO上看过几次).我也不喜欢它,因为它们依赖于跟踪GC在不再强烈引用之后可能不会立即收集对象的事实,除非在低内存情况下.这些类型的情况对于引用计数GC是完全无效的,因为对象在不再被引用之后立即被销毁(除了可能在循环的情况下).

但这真让我感到疑惑:弱引用怎么可能有用呢?如果你不能指望它引用一个对象,并且它不需要像打破周期那样,那么为什么要使用它?

weak-references

35
推荐指数
3
解决办法
7358
查看次数

理解ConditionalWeakTable

我想了解ConditionalWeakTable.有什么区别

class ClassA
{
    static readonly ConditionalWeakTable<ClassA, OtherClass> OtherClassTable
        = new ConditionalWeakTable<ClassA, OtherClass>();
}
Run Code Online (Sandbox Code Playgroud)

和

class ClassB
{
    OtherClass otherClass;
}
Run Code Online (Sandbox Code Playgroud)

?使用ClassA或ClassB引用可空字段的优缺点是什么?

.net dictionary weak-references

12
推荐指数
2
解决办法
1万
查看次数

弱引用与设置为 Null

使用 Wea​​kReference 和将强引用类型设置为 null 之间有什么区别?

例如,在下面的代码中,变量“test”是对“testString”的强引用。当我将“测试”设置为空时。不再有强引用,因此“testString”现在有资格进行 GC。因此,如果我可以简单地将对象引用“test”设置为等于 null,那么拥有 WeakReference Type 的意义何在?

class CacheTest {
  private String test = "testString";

  public void evictCache(){
    test = null; // there is no longer a Strong reference to "testString" 
    System.gc(); //suggestion to JVM to trigger GC 
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么我想使用 Wea​​kReference ?

class CacheTest {
  private String test = "testString";
  private WeakReference<String> cache = new WeakReference<String>(test);

  public void evictCache(){
    test = null; // there is no longer a Strong reference to "testString" 
    System.gc(); //suggestion to …
Run Code Online (Sandbox Code Playgroud)

java weak-references

5
推荐指数
1
解决办法
1118
查看次数

标签 统计

weak-references ×3

.net ×1

dictionary ×1

java ×1