Here is what Ehcache official documentation says about Sizing of cached entries:
Sizing of cached entries
Elements put in a memory-limited cache will have their memory sizes
measured. The entire Element instance added to the cache is measured,
including key and value, as well as the memory footprint of adding
that instance to internal data structures. Key and value are measured
as object graphs – each reference is followed and the object
reference also measured. This goes on recursively.
Shared references will be measured by each class that references it.
This will result in an overstatement. Shared references should
therefore be ignored.
Configuration for Limiting the Traversed Object Graph
Sizing caches involves traversing object graphs, a process that can be limited with annotations. This process can also be controlled at both the CacheManager and cache levels.
Control how deep the size-of engine can go when sizing on-heap elements by adding the following element at the CacheManager level in resources/ehcache.xml
<sizeOfPolicy maxDepth="100" maxDepthExceededBehavior="abort" />
This element has the following attributes:
maxDepth
which controls how many linked objects can be visited before the size-of engine takes any action. This attribute is required.
maxDepthExceededBehavior
which specifies what happens when the max depth is exceeded while sizing an object graph. Possible values for this filed are:
continue
which forces
the size-of engine to log a warning and continue the sizing
operation. If this attribute is not specified, continue
is the
behavior used
abort
which forces the size-of engine to abort the
sizing, log a warning, and mark the cache as not correctly tracking
memory usage. With this setting, Ehcache.hasAbortedSizeOf()
returns
true
The SizeOf policy can be configured at the cache manager level
(directly under <ehcache>
) and at the cache level (under <cache>
or
<defaultCache>
). The cache policy always overrides the cache manager
one if both are set. This element has no effect on distributed
caches.