According to this question, the standard way to determine the memory size of an object in Java is by using java.lang.instrumentation. After to some research, it looks like there is no Scala specific way to achieve this, so the Java approach should also applies here.
Unfortunately, for a Scala programmer without Java background it is not fully straightforward to adapt this technique in Scala. My questions are:
Question 1
What exactly is happening here? I guess the reason why we have to put a class like ObjectSizeFetcher
in a separate JAR is to ensure that it is somehow loaded before the actual program where we want to use it. I assume it is not possible to use instrumentation without the Premain-Class
entry and the parameter -javaagent:TheJarContainingObjectFetcher.jar
?
Question 2
Is there a simple way to implement the complete work flow in SBT? Currently I only see a somewhat cumbersome solution: I first have to set up a secondary SBT project where I define ObjectSizeFetcher
and package it into a JAR. So far I did not figure out how to automatically add the Premain-Class
entry to the JAR during packaging, so I would have to solve that manually. Than I can add the resulting JAR to the local libraries of the project where I want to use getObjectSize
. For this project I now have to enable fork in run
and use javaOptions in run += "-javaagent:TheJarContainingObjectFetcher.jar"
. Is there a more simple (and less intrusive) work flow to quickly use instrumentation within an existing SBT project? Maybe I can tell SBT directly about a Premain-Class
to make this secondary JAR unnecessary?
Question 3
Would you recommend a completely different way to evaluate the memory usage of an object in Scala?