Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are weak references implemented?

I wonder how weak references work internally, for example in .NET or in Java. My two general ideas are:

  1. "Intrusive" - to add list of weak references to the most top class (object class). Then, when an object is destroyed, all the weak references can be iterated and set to null.
  2. "Non-intrusive" - to maintain a hashtable of objects' pointers to lists of weak references. When a weak reference A is created to an object B, there would be an entry in the hashtable modified or created, whose key would be the pointer to B.
  3. "Dirty" - to store a special hash-value with each object, which would be zeroed when the object is destroyed. Weak references would copy that hash-value and would compare it with the object's value to check if the object is alive. This would however cause access violation errors, when used directly, so there would need to be an additional object with that hash-value, I think.

Either of these solutions seems clean nor efficient. Does anyone know how it is actually done?

like image 363
Michal Czardybon Avatar asked Apr 23 '09 08:04

Michal Czardybon


People also ask

How does a weak reference work?

A weakly referenced object is cleared by the Garbage Collector when it's weakly reachable. Weak reachability means that an object has neither strong nor soft references pointing to it. The object can be reached only by traversing a weak reference.

What is weak reference in Java and how it is used?

Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings. Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable.

Why do you need weak references?

Weak Refernce Objects are needed to JVM platform to ensure means against the memory leaks.


2 Answers

In .NET, when a WeakReference is created, the GC is asked for a handle/opaque token representing the reference. Then, when needed, WeakReference uses this handle to ask the GC if that handle is still valid (i.e. the original object still exists) - and if so, it can get the actual object reference.

So this is building a list of tokens/handles against object addresses (and presumably maintaining that list during defragmentation etc)

I'm not sure I 100% understand the three bullets, so I hesitate to guess which (if any) that is closest to.

like image 61
Marc Gravell Avatar answered Oct 19 '22 20:10

Marc Gravell


Not sure I understood your question, but you can have a look at the implementation for the class WeakReference and its superclass Reference in Java. It is well commented and you can see it has a field treated specially by the GC and another one used directly by the VM.

like image 39
pgras Avatar answered Oct 19 '22 18:10

pgras