On the garbage collection

It’s needed whenever you are using manipulating what belong to an object without using an reference to that object.

The only way this can cause crash is obviously when you have unsafe code (mostly pointers) since you aren’t supposed to get crashes in any other way. (If you do it’s not your but bug julia bug). However, you may also need it, boardly speaking if you extend the definition of what object owns what, as shown below.

In the most abstract sense, everything you are operating on is owned by some object and as long as you can figure this ownership out then you’ll have no problem writing correct code. Usually the owner is the object you are manipulating but when it isn’t then that’s when you need to be careful. The most obvious example is certainly pointers. When you pass them around, unless you are just using them as random bit patterns, the memory operetion you do on the pointer belongs to whereever you get that pointer from and you need to preserve that object using one of the few mechanisms.

Now, apart from pointers, you can certainly define you own ownership and assign one non-pointer object to be owned by another object, i.e. I can have a = A(); b = B() and just say b actually belongs to a as the “contract” in my API. However, for this to be of any significance/necesity the freeing/destruction of the owner must have an effect on the object being owned. Apart from the memory itself this pretty much only happen with finalizers. As an example if you have b = Ref{Int}(1); a = Ref{typeof(b)}(b) and add an finalizer to a that clears b to 0. In order for b to be valid (non-zero) you now need to make sure a is preserved during the operation. (Note that this case is also very subjective and is entirely up to the creater of the API to determine the ownership. b having a value of 0 might be entirely valid for example and is merely keeping count of something)

Another way of seeing this is that we have normal memory that is managed by the compiler/GC and we have object/memory that is managed by the finalizer. The normal memory always has an object attached as owner and the finalizer is also always registered to an owner object. You just need to figure out if the validity of an object/memory/things is managed as normal object memory or by a finalizer, and then you can figure out the owner easily from there.


In short, you need to figure out the owner of whatever you are operating on. It is pretty much part of the API what the owner is and an object that is now owned by itself should be explicited documented one way or another. Pretty much the only two ways this can happen is from derived pointer and finalizers so you should get a pretty good guess without looking.

7 Likes