简体   繁体   English

我该如何通过代码进行Java对象分配跟踪

[英]how can I do java object allocation tracing from with code

I'm using java profilers to check GC performance - but its very hit and miss. 我正在使用Java事件探查器来检查GC性能-但是它非常容易出错。 What I'd really like to do is to embed some real world profiling into my app. 我真正想做的是在我的应用程序中嵌入一些真实世界的配置文件。 It's very easy for time profiling - ie marking time and subtracting, but I can't find any way of doing it from memory. 时间分析非常简单-即标记时间和减去时间,但是我找不到从内存中做任何事情的方法。

Essentially - I want to make a function like this: 本质上-我想做一个这样的功能:

 ProfileResult  profile( Runnable function)

that gives me back information about memory allocation - ie how many objects, how many bytes were allocated - and how much of that could be garbage collected. 这给了我有关内存分配的信息,即分配了多少个对象,分配了多少个字节以及其中有多少可以被垃圾回收。

What I want to end up with is tests in our CI system that basically get upset at things like function has increased its memory pressure... and that are definitively correct - they actually know that this new function allocates 200 bytes more than the old one - its not just a random snap of time where all sorts of other things could happen in other threads, or garbage collections could have happened or whatever. 我要结束的是在CI系统中进行的测试,这些测试基本上使诸如函数之类的事情烦恼,从而增加了其内存压力……而且绝对正确—他们实际上知道,这个新函数比旧函数分配了200个字节-这不仅是随机的时间,在其他线程中可能还会发生其他各种事情,或者可能发生了垃圾回收等等。

Is this possible? 这可能吗? I know the JVM has profiling functionality built in - is it possible to access it from within the program which is running - or is there any other way to achieve what I want? 我知道JVM具有内置的性能分析功能-是否可以从正在运行的程序中访问它-还是有其他方法可以实现我想要的功能?

Analysis of JVM heap dumps can be integrated into CI and (hypothetically) give you all information you are looking for. 可以将JVM堆转储的分析集成到CI中,并(假设)为您提供所需的所有信息。

Idea is simple, you are taking heap dump before and after function being tested. 想法很简单,您要在测试功能前后进行堆转储。 Then you can analyze difference and assert certain SLA of code being tested. 然后,您可以分析差异并声明要测试的代码的某些SLA。

In past, I was automated heap dump analysis to verify correct resource disposal. 过去,我曾进行过自动堆转储分析,以验证正确的资源处理方式。 Some utility code is available as open source https://github.com/aragozin/heapunit/ . 一些实用程序代码可以作为开源https://github.com/aragozin/heapunit/获得 Though, that library does not support heap diff based analysis. 但是,该库不支持基于堆差异的分析。

Using heap dump based approach may have other down sides 使用基于堆转储的方法可能还有其他缺点

  • performance / disk space usage if you JVM have large heap 如果JVM具有大堆,则性能/磁盘空间使用率
  • in accurate object allocation profiling in GC is invoked between two dumps 在两个转储之间调用GC中准确对象分配的过程

If you need just track amount of bytes allocated by piece of code on single thread take a look on this snippet of code it is using per thread allocation counter available via JMX. 如果您只需要跟踪单线程上一段代码分配的字节数,请查看此代码段,它使用的是通过JMX提供的每个线程分配计数器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM