When an array of objects is not referenced anymore, does the objects in that array are garbage collected too? (assuming no variables are referencing the elements)
In this page, http://java.sys-con.com/node/37613 it says - "The biggest danger is placing an object into a collection and forgetting to remove it. The memory used by that object will never be reclaimed."
If you make sure to nullify the references, why will that memory be unclaimed?
Thanks
As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.
Garbage collection in Java is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically.
The garbage collection implementation lives in the JVM. Each JVM can implement garbage collection however it pleases; the only requirement is that it meets the JVM specification. Although there are many JVMs, Oracle's HotSpot is by far the most common.
When an array of objects is not referenced anymore, does the objects in that array are garbage collected too? (assuming no variables are referencing the elements)
Yes.
"The biggest danger is placing an object into a collection and forgetting to remove it. The memory used by that object will never be reclaimed."
This is when you are holding a reference to the collection. For example, if you have a Map
in which you put a key-value and then forget to remove then it stays there for ever. Think http sessions, if you use something in ServerContext
or some such at start of request using session id as key but fail to remove it at end of the request processing..
For the first question, the answer is yes, absolutely: the objects inside non-referenced array and no other references do get garbage collected.
As for the second question, the document talks about placing forgetting an object inside a referenced collection, for example a cache of some sort, a static field, a thread-local store, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With