simple question about garbage collection

B

bkazlak

Hello,

I have a quick question might help me understand garbage collection.

let's say I'm having a static collection of objects in one class, so
this collection should be cached and present all time. Now if a method
in another object clones this collection, when would be the cloned
collection eligible for garbage collection? when the method goes out of
scope?

thank you.
 
D

Daniel O'Connell [C# MVP]

Hello,

I have a quick question might help me understand garbage collection.

let's say I'm having a static collection of objects in one class, so
this collection should be cached and present all time. Now if a method
in another object clones this collection, when would be the cloned
collection eligible for garbage collection? when the method goes out of
scope?

Yes, basically(it actually becomes eligiable as soon as the GC cannot find a
reference, which means immediatly after its last use), although what exactly
gets collected is a matter of how you clone the collection.
 
J

Jeff Louie

As I understand it... If you clone an _instance_ arraylist of mutable
objects (as opposed to values) you get a shallow copy of the references
in the arraylist. So now you can touch and alter the state of the single
set of mutable objects using the cloned array of references. You can
re-sort the cloned arraylist and it will have no effect on the sort
order of the original array list of references.

When the copy of the arraylist is no longer _reachable_ by any code, the
cloned arraylist of references is eligible for garbage collection. If
the cloned arraylist is only reachable by a local variable, then the
cloned arraylist is eligible for gc when that local variable goes out of
scope. If the original arraylist is still reachable, then any objects
reachable through the original arraylist are not eligible for gc.

Now it gets more complicated. If you don't want the caller to be able to
alter the mutable objects in the original arraylist, you must either
wrap the arraylist by reference in a read only wrapper class or pass a
deep copy of the arraylist so that you clone both the arraylist and all
the mutable objects so that the references in each arraylist refer to a
different set of objects on the heap.

The special exception is an arraylist of strings. Since strings are
immutable you can safely pass a shallow copy of an arraylist of strings.
If the user of the clone tries to reassign a bucket in the cloned
arraylist to a new string, the bucket is assigned to a new immutable
string. The same bucket in the original arraylist still refers to the
original string object.

Regards,
Jeff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top