How are weak arrays used?

The question says it all. I have a data structure that I cannot marshal due to a weak hash table .. I wonder if I can get rid of it :)

+6
ocaml
source share
2 answers

A weak array is an array of weak pointers. A weak pointer is a reference to a value that can be garbage collected.

If you use a regular pointer to a value, you will prevent it from collecting garbage until the referee collects the garbage. With weak reference, the value may be collected before the judge.

An example of use is a source that transmits data to multiple receivers. If the source has regular pointers to the receivers, whenever the receiver is no longer needed, it will not collect garbage until the source is there (which, for example, will never happen). If the source uses weak receiver references, these receivers can be garbage collected before the source.

Another example is hashconsing for a type that uses weak hashtables (which include weak arrays). Quickly, hashconsing is a way to remember all the values ​​of a given type that are created and live in the program. Together with the corresponding constructor of values, this can provide maximum separation of values ​​of this type and allows realizing structural equality in this type as physical equality. In this case, if a non-weak hash table is used, values ​​that are no longer used by the program will never collect garbage.

Finally, many people think (erroneously) that weak links are useful for implementing caches. Keep a weak reference to the value, if it was garbage collection, reload / recount the value. This is not a good caching algorithm, since the main garbage collection returns any value that is no longer referenced. Thus, your caching algorithm does not have predictability or a useful property, for example, the size of the cache / available memory does not exceed the specified ratio.

+11
source share

Use a bijective pair of mapping functions between your data structure and its structurally congruent representation compatible with the Marshall module.

+1
source share

All Articles