That’s it! We’ve finally done it… Or almost done it. We’ve extracted the SizeOf code from the Ehcache library in it’s own library.
The first release of the lib was just pushed to maven central and available by adding the following dependency to your pom.xml:
<groupId>org.ehcache</groupId> <artifactId>sizeof</artifactId> <version>0.2.0</version>
It then can simply be used by creating a new SizeOf instance (optionally passing some filters in) and using one of two methods:
SizeOf sizeOf = SizeOf.newInstance(); // <1> sizeOf.sizeOf("Some string"); // <2> sizeOf.deepSizeOf(Integer.MAX_VALUE, false, new ReentrantReadWriteLock()).getCalculated(); // <3>
- Creates a new instance, but also (only the first time) determines which of the 3 implementations will be used (see below)
- Sizes the
java.lang.Stringinstance passed in
- Sizes the
ReentrantReadWriteLockinstance, but also navigates down the graph, returning a
Sizeinstance. The two first arguments limit the amount of references the graph will be walked down for, and what to do if we hit this limit: either throw (
true), or ignore and return the size calculated until the limit was reached (
The first time you invoke
SIzeOf.newInstance(), the library will try to load one of the three implementations that we currently have:
UnsafeSizeOf and finally
The library will try to attach to the Java virtual machine process and load an agent (packaged within the sizeof jar). If that succeeds, the
AgentSizeOf will use
java.lang.instrument.Instrumentation#getObjectSize to measure individual object sizes.
Should the attempt to attach to the VM fail, the
UnsafeSizeOf is used. At least if we manage to access the
sun.misc.Unsafe instance to then use that to calculate size, mainly with
If all that failed, we’ll fallback to Java’s Reflection API to “manually” calculate object sizes.
Well… yes and no. Yes, we believe it is fairly stable and well tested. It is what Ehcache has been using for a while now… Yet, we are not API (/ˈhapē/) with the API. Mainly
org.ehcache.sizeof.Size, and the deepSizeOf method signature. These are left overs from the port that we still want to clean up. Finally, this release has support for OpenJDK, which we didn’t use to support.
And tell us what you think. In the meantime will be clearing those leftovers for the next release and a couple of other enhancements. All tracked on Github at https://github.com/Terracotta-OSS/ehcache-sizeofengine Feel free to submit bugs, ideas and, why not, matching pull requests!