如何测试依赖于SoftReference的代码?

时间:2015-06-25 16:39:15

标签: java unit-testing garbage-collection

我有一些代码使用了许多SoftReference子类的实例。我想测试一下,当ReferenceQueue中的所有/只有一些/没有这些参考被分阶段清算时,它可以正常工作。对于"无"这很容易:创建对对象的强引用,并保证软引用保留。但是,我如何保证清除它们呢?据我所知,System.gc()只是一个运行垃圾收集器的请求,即使它实际运行,也可能决定不收集所有无法访问的对象......

此外,代码对性能至关重要,因此仅为测试目的而改变代码并不是一个好主意。 (添加一个不影响其他方法的仅测试方法很好,但添加仅用于在其他方法中测试的路径是可以避免的。)

1 个答案:

答案 0 :(得分:1)

If it is an option to access your SoftReference instances from the test you could simulate the GC behavior by calling methods directly on the SoftReference instances.

Calling SoftReference.clear() would correspond to the first step where the reference is cleared. Then you could call SoftReference.enqueue() to enqueue it in the reference queue, corresponding to the enqueing step the GC does [some time] after clearing the reference.

Calling these methods on a subset of your SoftReferences you could simulate that only some of the references have been cleared and enqueued.

I really think the above approach is to recommend since you got control of which references are cleared and that is a good thing in a test.

However, if you can not access your SoftReferences directly you are pretty much limited to allocating memory in an attempt to make the GC clear them. For example, as illustrated in this question and its answers.