YourKit - The retained size of an object doesn't equal the retained size of all the objects referred by it
Asked Answered
P

1

13

The retained size of an object doesn't equal the retained size of all the objects referred by it.

Here is what is happening:

  1. Using YourKit to capture memory snapshot.
  2. click on an object & show instances by class type
  3. let's say the instance's retained memory is A bytes (600mb)
  4. expand and sum the retained size for the underlying instances let's say the sum is B (300mb)

A >> B

Poniard answered 29/5, 2014 at 19:44 Comment(2)
B >> A would be a real mystery. I'm guessing alignment or metadata, but I have no idea.Scribbler
Well I was hoping for A ~= B (almost the same)Poniard
E
18

Let me give you an example.

First of all, you need to understand what retained size is. From the official documentation:

Retained size of an object is its shallow size plus the shallow sizes of the objects that are accessible, directly or indirectly, only from this object. In other words, the retained size represents the amount of memory that will be freed by the garbage collector when this object is collected.

In a simple the retained size of an object will indeed be the sum of the objects referred by it. In the picture below the retained size of Obj1 is the sum of the Obj1 shallow size, and Obj2 and Obj3 retained size: simple case

This is not the case in more complicated referencing models. If Obj6 starts referencing Obj5, then Obj5 will not be accessible only from Obj2. So the retained size of Obj2 will now include only Obj4, and will exclude Obj5. retained size of Obj1 is not a sum of Obj2 and Obj3 The retained size of Obj1 will stay the same. If garbage collector frees Obj1, it'll free the whole references graph of size 41. However, if garbage collector frees only Obj2, it will not free Obj5, because it would be still referenced by Obj6.

Edin answered 2/2, 2017 at 23:34 Comment(1)
Good answer. It seems like this makes heap dumps tricky to read sometimes. In your second example, Obj5 is not included in the retained size of Obj2 or Obj3; it's included in the retained size of Obj1 only. In a complicated heap dump, Obj5 could be nested many levels deep. Do you have any suggestions for dealing with this when investigating memory leaks?Salesperson

© 2022 - 2024 — McMap. All rights reserved.