Today in my interview , i was asked to write a code to determine how many instances for a class exits at runtime in java.
I told them , that we can use reflection . kindly let me know if you have efficient way of doing this.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I don’t think reflection will help you. There is the JVMTI (and the older and now defunct JVMPI) which can be used to analyse the heap and determine the number of current instances of a class.
A coded alternative is to add a counter to the class you want to track instances of:
This will track the number of instances ever created, and is thread-safe. To find out when instances are garbage collected, you can use a
PhantomReferenceand aReferenceQueueto track collected instances and decrement the counter.EDIT:
If the class is serializeable, implement the
readObjectmethod and increment the counter. I’ve added this to the first code example.