Say I have classes
class A{
//code for class A
}
class B{
//code for class B
}
class A{
public static void main(String a[]){
//Initialize m instances of A and n instances of B and store each in arrays
//Equate any arbit index in the array to null
}
}
In this scenario, my main goal is to find all active instances of classes A and B in the memory at any point.
I suppose it must be possible using a debugger.
However, due to some reason (the reason being beyond the scope of the question), I am required to get the instances from within the code itself. Thus, i need a function like
public void getAllActiveInstances(){
//Print values
}
Edit: I don’t need instances to operate over them. I just need to know whether they exist or not. This is mainly for debugging purposes.
If this is not possible then kindly explain how to do the same using debuggers.
The short answer is no, you should not be looking inside of memory at any time with java.
The long answer is, if there was any way of accessing an object after GC has collected it, then you are violating the GC’s principal of only collecting things that cannot be reached in any way by the executing code. Garbage collected memory is freed and returned to the program to do anything it wants with it. This means if you’ve GC’d an object A, java is allowed to write any number of things into that location, destroying the “A-ness” of that block of memory. Attempting to read an object B that is now stored in that memory block and pretending it’s an A will cause all sorts of problems.
Going forward: To keep track of all the classes you’ve created, I would suggest modifying the class itself. Your class can have a
staticcontainer (like aHashMap), and the constructor adds the constructed class to theHashMap. However, note that because you are hanging onto references to all of your created object, Garbage collect will never collect those objects and free up that memory.