测试弱参考 [英] Testing WeakReference

查看:24
本文介绍了测试弱参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中测试弱引用的正确方法是什么?

What is the proper approach to testing a weak reference in Java?

我最初的想法是做以下事情:

My initial idea is to do the following:

public class WeakReferenceTest {

    public class Target{
        private String value;    

        public Target(String value){
            this.value = value;
        }    
        public String toString(){
            return value;
        }
    }

    public class UsesWeakReference{    
        WeakReference<Target> reference;   

        public UsesWeakReference(Target test){
            reference = new WeakReference<Target>(test);
        }    
        public String call(){
            Target test = reference.get();
            if(test != null){
                return test.toString();
            }
            return "empty";
        }
    }

    @Test
    public void testWeakReference(){    
        Target target = new Target("42");

        UsesWeakReference usesWeakReference = new UsesWeakReference(target);    
        WeakReference<Target> triggerReference = new WeakReference<Target>(target);    
        assertEquals("42", usesWeakReference.call());

        target = null;    
        while(triggerReference.get() != null){
            System.gc();
        }

        assertEquals("empty", usesWeakReference.call());    
    }    
}

我对该方法的保留意见是使用 System.gc(),据我所知,它在不同的 JVM 上可能表现不同.

The reservation I have about the approach is using System.gc(), as I understand that it can behave differently on different JVMs.

推荐答案

没有 100% 防弹的方法来测试使用引用类型的代码.Reference 对象的行为取决于 GC 何时运行,并且没有 100% 可靠的方法来强制 GC 运行.

There's no 100% bombproof way of testing code that uses the Reference types. The behaviour of Reference objects depends on when the GC runs, and there is no 100% reliable way of forcing the GC to run.

你能做的最好的是:

  • 在运行测试时检查您是否设置了正确的 JVM 选项,并且
  • 编写您的测试,使其在 System.gc() 是空操作的情况下不会失败 OR 愿意禁用或跳过测试,或忽略测试失败.
  • check that you have the right JVM options set when running the tests, and
  • write your test so that it doesn't fail in the event that System.gc() is a no-op OR be willing to disable or skip the test, or ignore the test failure.

(您应该能够通过查看调用前后使用的内存量来检测 System.gc() 是否被忽略;例如,通过调用 Runtime.totalMemory())

(You should be able to detect that System.gc() is being ignored by looking at how much memory is in use before and after the call; e.g. by calling Runtime.totalMemory())

实际上,还有另一个解决方案".让你的单元测试产生大量的垃圾……足以保证你会触发垃圾收集.(IMO,这不是个好主意.)

Actually, there is another "solution". Have your unit test generate a huge amount of garbage ... enough to guarantee that you will trigger garbage collection. (Not a good idea, IMO.)

这篇关于测试弱参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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