Two-way WeakMap keeping objects alive?

62 views Asked by At

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?

2

There are 2 answers

1
Inspector Boat On
0
Bergi On

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.