Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A large network of objects that all have the same reference to an object

I have a large network of nodes in memory that all have a reference to the same object.

As an example. Let's assume each node in the network is this class.

public class Node
{
    /** This is the shared object **/
    public Context context { get; private set; }

    public Node Parent { get; private set; }

    public List<Node> Children { get; private set; }

    public Node(Context pContext, Node pParent, List<Node> pChildren)
    {
        this.context = pContext;
        this.Parent = pParent;
        this.Children = pChildren;
    }
}

The property context is an object that is passed to the constructor for all nodes in the network.

Assuming the network is very large (thousands of nodes), and they form a tree structure. Will this common shared reference among them lead to memory leaks?

If I detach a branch in the tree by setting Parent to Null. Will that branch be correctly garbage collection by C# even if context remains a reference to this shared object?

What coding practice should I employ to ensure this works correctly.

like image 366
Reactgular Avatar asked Jan 12 '23 14:01

Reactgular


2 Answers

Assuming the network is very large (thousands of nodes), and they form a tree structure. Will this common shared reference among them lead to memory leaks?

No, it shouldn't.

If I detach a branch in the tree by setting Parent to Null. Will that branch be correctly garbage collection by C# even if context remains a reference to this shared object?

Yes, it should. The only time this is potentially an issue is if you're subscribing to events on the longer lived objects, as event subscriptions create a reference to your class. Just holding a reference to context will not have any impact on allowing your class to be collected.

The main issue is that the objects will be garbage collected as soon as nothing can "reach" your object via references. Your objects can still hold references to other objects, it's only the other way around that matters.

like image 85
Reed Copsey Avatar answered Jan 21 '23 01:01

Reed Copsey


Your node references the context, so your node prevents the context from being garbage collected. Not the other way around.

Setting Parent to null will not result in that node being garbage collected. As long as your node is referenced from some other class, it will remain in memory.
In your concrete code, you need to remove the node from its parent's children for it to be garbage collected.

like image 36
Daniel Hilgarth Avatar answered Jan 21 '23 03:01

Daniel Hilgarth