测试使用 SoftReference的代码

发布于 2024-09-01 08:36:09 字数 198 浏览 0 评论 0原文

要使带有 SoftReference 的任何代码得到充分测试,必须想出某种方法来测试“是的,它已被置空”情况。人们可能会或多或少地通过使用“用于测试”的代码路径来强制引用为空来模拟这一点,但这不会像 GC 那样完全管理队列。我想知道是否有人可以分享设置可重复、受控环境的经验,在该环境中,GC 实际上会被激发进行收集和清零?

To get any code with SoftReference<T> to be fully tested, one must come up with some way to test the 'yup, it's been nulled' case. One might more or less mock this by using a 'for-test' code path to force the reference to be null, but that won't manage the queue exactly as the GC does. I wonder if anyone out can share experience in setting up a repeatable, controlled, environment, in which the GC is, in fact, provoked into collecting and nulling?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吻泪 2024-09-08 08:36:09

这个答案解释了如何强制使用“完整内存”进行垃圾收集。如果只是尝试分配比您拥有的更多的资源,这将会失败,但直到所有 SoftReference 都被清理干净。

This answer explains how you can force a garbage collect with 'full memory'. By just trying to allocate more than you have, which will fail, but not until all SoftReference have been clean up.

樱花坊 2024-09-08 08:36:09

我会将问题分为两部分:

  1. 返回 null 时测试代码路径。
  2. 测试软引用。

对于#1,我将使用一个返回 null 且具有足够变化(有时为 null,有时为真实对象)的 Mock 来测试您认为 GC 会遇到的所有相关场景。这就是单元测试。

接下来是真正的集成测试,看看 GC 的行为 WRT SoftReference 是否如您所期望的那样。我不确定我是否会努力完全自动化这样的测试,除非在更大的负载测试环境中,但如果这很重要,我会启动一个具有非常严格的最大内存量和负载的 JVM足够的内存来触发软引用收集。失败的路径是让代码不使用软引用,加载的内存应该会导致 OutOfMemory 错误。然后通过转换为软引用来使测试通过。测试的目的应该是断言单元测试中关于行为的假设。

I would break the problem up into two parts:

  1. Testing the code path when null is returned.
  2. Testing the SoftReference.

For #1 I would use a Mock that returns null with enough variation (sometimes null, sometimes real object) to test all of the relevant scenarios you think you will have with the GC. That would be the unit test.

The next is really an integration test, to see if the GC's behavior WRT SoftReference is as you expect. I'm not sure I would go to the effort to fully automate such a test, except in perhaps the larger context of load testing, but if that is important I would spin up a JVM with a very tight maximum amount of memory and load up enough memory to trigger soft-reference collection. The failing path would be to have the code not use a soft-reference, the memory loaded up should cause an OutOfMemory error. Then make the tests pass by converting to a soft-reference. The purpose of the tests should be to assert the assumptions made in the unit tests about the behavior.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文