Link to home
Start Free TrialLog in
Avatar of blairdye
blairdye

asked on

Arrays and Garbage Collection

I'm unsure of the specifics of garbage collection.
A class of mine has a String array that is initialised in the constructor:
Class MyClass{
 String myArray[];
MyClass(int size){
 myArray = new String[size];
}
Later I will want to reinitialize this array to another dynamic size and fill it with some other values. For this i have an update() method:
update(int size){
 myArray = new String[size];
}
By allocating a new object to myArray, I assume that I am making the old object available for garbage collection but not really actively cleaning it up. Is there a better way of doing this? Is my old object left hanging till the end of the program?
thanks, blair
Avatar of imladris
imladris
Flag of Canada image

You're doing fine. There is no way to improve on the situation. Java is a garbage collected environment. When you point myArray to a new array, the old is left without valid references to it, and the garbage collector will deal with it at some point, or when it needs to.
One of the joys of Java is, by and large, not having to worry about that stuff.
I think the old object will be automatically cleaned up but to make sure that happens I supose I'll have to do a

System.gc();

You can also test if everything is working ok by making:

for(;;){
update(...)
}

and see if you get an "out of memory".


Hope to have been helpful...
ASKER CERTIFIED SOLUTION
Avatar of mbormann
mbormann

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial