ThreadMXBean#getThreadAllocatedBytes是否会返回分配的内存或对象的大小? [英] Will ThreadMXBean#getThreadAllocatedBytes return size of allocated memory or objects?

查看:307
本文介绍了ThreadMXBean#getThreadAllocatedBytes是否会返回分配的内存或对象的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想雇用com.sun.management.ThreadMXBean做这样的事情:

long before = threadMxBean.getThreadAllocatedBytes(currentThreadId);
seriousBusiness(); // some calls here
long after = threadMxBean.getThreadAllocatedBytes(currentThreadId);
long allocDiff = after - before; // use for stats or whatever

问题是,此方法实际上返回什么:在方法调用时分配的新内存量或分配的对象的大小?要明确我的意思是什么:

1)假设我在seriousBusiness()调用中分配了一个巨大的数组,因此为此目的分配了一个新的内存区域,并且getThreadAllocatedBytes会增加相应的值.

2)经过一段时间,运行了GC,收集了未使用的阵列,并且内存区域现在​​可用.

3)我再次在同一线程中进行了一些调用,JVM看到它不需要分配新的内存,并且将该内存区域重新用于新用途,这导致getThreadAllocatedBytes值没有增长. /p>

关于JVM内存管理的工作方式,我可能并不十分精确,但是问题应该很清楚.

此外,如果第一个假设是正确的(仅计算新的内存分配),那么per-thread object allocations / memory footprint测量的正确方法是什么?

UPD.我试图检查一下自己: http://pastebin.com/ECQpz8g4 . (代码中的睡眠是为了让我能够使用JMC连接到JVM).

TL; DR:分配一个巨大的int数组,然后对其进行GC,然后分配一些新对象并检查已分配的内存.这是我得到的:

因此,看来GC实际上已在运行,并且在确实分配了内存并随后释放内存的同时,我得到了以下输出:

665328          // before everything started
4295684088      // 4 GiB allocated
4295684296      // did GC (for certain! (really?))
5812441672      // allocated a long string, took new memory

所以,我只是在等待一个对JVM内存有专门知识的人告诉我是对还是错在哪里.

解决方案

引用http://pastebin.com/ECQpz8g4. (sleeps in the code are to allow me to connect to the JVM with JMC).

TL;DR: Allocate a huge int array, then GC it, then allocate some new objects and check allocated memory. Here's what I got:

So, it appears that GC was actually run and, while memory was certainly allocated and subsequently freed, I got this output:

665328          // before everything started
4295684088      // 4 GiB allocated
4295684296      // did GC (for certain! (really?))
5812441672      // allocated a long string, took new memory

So, I'm just waiting for someone with expertise on JVM memory to tell me if I'm right or where am I wrong.

解决方案

Referencing ThreadMXBean, it reports the number of bytes allocated in heap on behalf of the target thread, but it is implied that this is equivalent to the size of the objects allocated. There is a caveat though:

The returned value is an approximation because some Java virtual machine implementations may use object allocation mechanisms that result in a delay between the time an object is allocated and the time its size is recorded

Therefore, I would assume that reclamation of heap space has no effect on the reported values, since it is only reporting the absolute number of bytes allocated, so if you allocate 100 bytes, then 80 bytes are reclaimed, and then you allocate another 100 bytes, the reported (delta) value at the conclusion of these events would be 200 bytes, although the net allocation was only 120.

这篇关于ThreadMXBean#getThreadAllocatedBytes是否会返回分配的内存或对象的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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