ThreadMXBean.getThreadAllocatedBytes() allocates memory

Bengt Rutisson bengt.openjdk at gmail.com
Sun Sep 18 21:14:37 UTC 2016


Hi Serviceability,

Not sure, but I hope this is the correct list to post this on.

I wanted to use the ThreadMXBean.getThreadAllocatedBytes() method to get
some information about how much memory some Java code allocated.

When I dug into the results they didn't properly add up until I realized
that the call to getThreadAllocatedBytes() actually allocates memory. This
was a surprise to me.

I'm attaching a small example to illustrate what I mean.

Running the example renders this output:

$ javac AllocMeasure.java
$ java AllocMeasure
Bytes allocated: 48
Bytes allocated: 48
Bytes allocated: 48
Bytes allocated: 48
Bytes allocated: 48
Bytes allocated: 48
Bytes allocated: 48
Bytes allocated: 48
Bytes allocated: 48
Bytes allocated: 48

What I would have expected was that it would say "Bytes allocated: 0" since
I would like to add my own code between line 9 and 10 in the example and
get the value for how much memory it allocates. As it is now I have to
deduct the bytes that the getThreadAllocatedBytes() allocates to get the
correct result.

The problem is that getThreadAllocatedBytes() is implemented this way:

    public long getThreadAllocatedBytes(long id) {
        long[] ids = new long[1];
        ids[0] = id;
        final long[] sizes = getThreadAllocatedBytes(ids);
        return sizes[0];
    }

http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/32d957185656/src/java.management/share/classes/sun/management/ThreadImpl.java#l345

I was surprised to see the "new long[1]". I realize that it is nice to
reuse getThreadAllocatedBytes(long []) method, but maybe a pre-allocated
array can be used instead of allocating a new one for each call?

I know the specification for this method is kind of fuzzy, but is this to
be considered a bug or does it work as intended?

Thanks,
Bengt
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/serviceability-dev/attachments/20160918/349fb53c/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: AllocMeasure.java
Type: application/octet-stream
Size: 531 bytes
Desc: not available
URL: <http://mail.openjdk.java.net/pipermail/serviceability-dev/attachments/20160918/349fb53c/AllocMeasure.java>


More information about the serviceability-dev mailing list