Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays and Garbage collection in Java

Let us say I have an Array a, where the array is of type T. Would setting an element to null mark it for garbage collection.

For example, If I do a[36] = null, or do I need to something more, like also set fields in that object of type T tonull?

like image 304
pythonic Avatar asked Dec 18 '25 05:12

pythonic


1 Answers

In Java, objects are stored on the heap, whereas variables/references are stored on the stack. The GC performs what is called a 'cycle', which checks which variables no longer refer to actual datatypes, as well as checking if objects are still referred to in the scope. As mario mentioned, an object will eventually be collected when nothing holds a reference to it, however in some performance/memory critical applications, setting objects to null and trying to speed up the garbage collection process has been known to provide marginal performance benefits. In this case, I wouldn't worry about it too much.

like image 140
Martin McKeaveney Avatar answered Dec 20 '25 21:12

Martin McKeaveney