开发者

Testing code that uses SoftReference<T>

开发者 https://www.devze.com 2022-12-30 11:35 出处:网络
To get any code with SoftReference<T> to be fully tes开发者_运维问答ted, 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 \

To get any code with SoftReference<T> to be fully tes开发者_运维问答ted, 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号