• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 191
  • Last Modified:

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
0
blairdye
Asked:
blairdye
1 Solution
 
imladrisCommented:
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.
0
 
filipecorreiaCommented:
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...
0
 
mbormannCommented:
u can help speed up the work of the GC by doing this

update(int size)
{
//set the previous Object reference to null
      myArray = null;

      myArray = new String[size];
}

which will mean that the JVM which has this 'myArray' reference in it's table of Object pointers will be set to null,and this can be removed to the table of Objects to be garbage collected.

I have noticed that this is not often followed in Sun's own code,perhaps this may have helped in Old JVM's but in newer ones like HotSpot this may have no effect?

Calling System.gc() was supposed to be a expensive operation for cases where the memory to be cleaned up is less,definitely u can try that for bigger chunks of memory.

Again in newer ones like HotSpot this may have no noticeable effect on ur program ,and u have no need to call gc() in the first place at all?

Blair,why dont u use a Vector instead of a Array as it's supposed to be used in places where u want a Growable Array.
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now