java 内存测试,Java单元测试:如何测量方法调用的内存占用量

本文探讨了如何确保一个执行大量处理并操作多个集合的Java类不会导致内存溢出。提出了几种可能的解决方案,包括通过微基准测试估算内存需求、基于启发式方法构建分配策略、利用Guava的缓存实现基于内存的驱逐策略,以及编写基准测试来测量内存分配。此外,还介绍了使用System.gc()和内存计算来粗略估计方法的内存占用。
摘要由CSDN通过智能技术生成

Assuming I have a class that does some heavy processing, operating with several collections. What I want to do is to make sure that such operation can't lead to out-of-memory or even better I want to set a threshold of how much memory it can use.

class MyClass()

{

public void myMethod()

{

for(int i=0; i<10000000; i++)

{

// Allocate some memory, may be several collections

}

}

}

class MyClassTest

{

@Test

public void myMethod_makeSureMemoryFootprintIsNotBiggerThanMax()

{

new MyClass().myMethod();

// How do I measure amount of memory it may try to allocate?

}

}

What is the right approach to do this? Or this is not possible/not feasible?

解决方案

I can think of several options:

Finding out how much memory your method requires via a microbenchmark (i.e. jmh).

Building allocation strategies based on heuristic estimation. There are several open source solutions implementing class size estimation i.e. ClassSize. A much easier way could be utilizing a cache which frees rarely used objects (i.e. Guava's Cache). As mentioned by @EnnoShioji, Guava's cache has memory-based eviction policies.

You can also write your own benchmark test which counts memory. The idea is to

Have a single thread running.

Create a new array to store your objects to allocate. So these objects won't be collected during GC run.

System.gc(), memoryBefore = runtime.totalMemory() - runtime.freeMemory()

Allocate your objects. Put them into the array.

System.gc(), memoryAfter = runtime.totalMemory() - runtime.freeMemory()

This is a technique I used in my lightweight micro-benchmark tool which is capable of measuring memory allocation with byte-precision.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值