Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared Variables and Garbage Collection

I've been doing some reading on garbage collection in .NET and I was hoping for some clarification. So, as I understand it if I declare a public shared class variable, the GC will never get rid of it. Is this correct?

Also, what then of private variables? Take the following example:

public class myClass
    private shared myString As String

    public sub ChangeString(newString As String)
        myString = newString
    end sub
end class

Would the shared variable now get GCed if there were no instances of the class? And what if I alter ChangeString to be a shared sub?

like image 225
geekchic Avatar asked Feb 21 '12 18:02

geekchic


Video Answer


2 Answers

So, as I understand it if I declare a public shared class variable, the GC will never get rid of it. Is this correct?

Almost. The GC will not clean up the string that your Shared variable references.

If, however, you call ChangeString with a new string, the string that was pointed to by myString will no longer be rooted by this reference, and may be eligible for GC. However, the new string (referenced by newString) will now become rooted by the myString variable, preventing it from garbage collection.

Would the shared variable now get GCed if there were no instances of the class?

No. The shared variable roots the object, since it's owned by the "type" of the class, not any instances.

And what if I alter ChangeString to be a shared sub?

This will have no effect at all.

like image 101
Reed Copsey Avatar answered Oct 16 '22 09:10

Reed Copsey


The shared variable lives in the class itself, so you don't need an instance of the class for the variable to survive, so your string would not be garbage collected.

It doesn't matter if a variable is private, it still won't be garbage collected. It doesn't matter if you use a sharded method or an instance method to set the variable.

Note: The garbage collector never collects variables, it only collects objects.

like image 38
Guffa Avatar answered Oct 16 '22 09:10

Guffa