5

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

1
  • Because if you don't nullify the references, it won't be reclaimed. Commented Mar 9, 2012 at 1:45

4 Answers 4

4

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..

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

It won't be unclaimed if nothing references it. The article says that if you nullify a reference, but the object is still in a referenced collection (hence referenced), it won't be collected.

Comments

1

Generally speaking, anything that's not referenced is garbage collected. So, yes, those objects would be garbage collected.

Also, note that:

  1. An array is not a collection.
  2. I think that what the person that wrote that meant was make sure you remember all of the places you're referencing an object, so that if you intend to remove it, it gets removed (and there are no lingering references to it).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.