tags:

views:

145

answers:

2

Let's say I have a class Collection which holds a list of Items.

public class Collection
{
    private List<Item> MyList;
    //...
}

I have several instances of this Collection class which all have different MyLists but share some Items. For example: There are 10 Items, Collection1 references Items 1-4, Collection2 has Items 2-8 and Collection3 4,7,8 and 10 on its List.

I implemented this as follows: I have one global List which holds any Items available. Before I create a new Collection I check if there are already Items I need in this list -- if not I create the Item and add it to the global List (and to the Collection of course).

The problem I see is that those Items will never be released - even if all Collections are gone, the memory they consume is still not freed because the global list still references them. Is this something I need to worry about? If so, what should I do? I thought of adding a counter to the global list to see when an Item is not needed anymore and remove its reference.

Edit: It is in fact a design problem, I think. I will discard the idea of a global list and instead loop through all Collections and see if they have the needed Item already.

+2  A: 

If the global list needs references to the items then you can't realistically free them. Do you actually need references to the items in the global list? When should you logically be able to remove items from the global list?

You could consider using weak references in the global list, and periodically pruning the WeakReference values themselves if their referents have been collected.

Jon Skeet
Thanks for mentioning weak references - I didn't know about them. But I don't think they are relevant for my problem.
CaptainProton
+1  A: 

It looks like a bit of a design problem, do you really need the global list?

Apart from weakreferences that Jon mentions, you could also periodically rebuild the global list (for example after deleting a collection) or only build it dynamically when you need it and release it again.

You'll have to decide which method is most appropriate, we don't have enough context here.

Henk Holterman