Goldman Sachs Interview Question
Java DevelopersCountry: India
Interview Type: In-Person
posting the contents here:
You can use the java.lang.instrument package
Compile and put this class in a JAR:
import java.lang.instrument.Instrumentation;
public class ObjectSizeFetcher {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object o) {
return instrumentation.getObjectSize(o);
}
}
Add the following to your MANIFEST.MF:
Premain-Class: ObjectSizeFetcher
Use getObjectSize:
public class C {
private int x;
private int y;
public static void main(String [] args) {
System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
}
}
Invoke with:
java -javaagent:ObjectSizeFetcherAgent.jar C
The intent of the interviewer is certainly Reflection, but you can serialize the object and calculate the number of bytes stored, as well. The same approach should work for different objects and give a relative "size" which can then be compared.
The writeObject method should be overridden such that only the member variables of the object are serialized. (Since we are talking about containers). Then a bytecount would return reliable comparison results. This should work since all objects are custom serialized the same way,
Just food for thought.
stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object
- subahjit July 09, 2013