1

Assume I have two WeakMaps:

a2b = new WeakMap<A, B>();
b2a = new WeakMap<B, A>();

If I now do:

a2b.set(a, b);
b2a.set(b, a);

Will this keep both a and b alive or will they be finalized if nobody else is holding on to either a or b?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
user3612643
  • 5,096
  • 7
  • 34
  • 55
  • Have you tested it? – Daniel A. White May 26 '22 at 11:39
  • I think only the values are held weakly, and the keys are held strongly – Daniel A. White May 26 '22 at 11:58
  • 1
    I would guess, that they would both be garbage collected because if nobody else is holding on to `a` or `b` you would not be able to retrieve any of the values since you always need `a` or `b` and the `WeakMap` to retrieve a value. The values can therefore not be used, so why keep them. But that's just my guess, not knowledge. Interesting question though. Hoping to see some JS experts come to rescue :D – Mushroomator May 26 '22 at 11:58
  • @DanielA.White No, a `WeakMap` is not a `Map` containing `WeakRef`s as values. Nothing is held strongly but the reference from the key to the value. – Bergi Oct 12 '22 at 03:12

2 Answers2

0

They will be garbage collected. Firefox has about:memory, which allows you to manually trigger garbage collection across pages.

0

No, this will not keep the objects alive.

Liveness is determined by reachability from the gc roots, not from circular reasoning. If nothing else keeps the objects alive, they will get garbage-collected - the cyclic dependency on each other's liveness does not matter.

The a object will be kept alive if both b and b2a are alive.
The b object will be kept alive if both a and a2b are alive.
If both are dead, they won't keep each other alive.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375