Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would a "circular" reference be treated as "reachability" for a WeakMap?

function f() {
  const w = new WeakMap();
  const o = {};

  w.set(o, { v: o });

  return w;
}

const weakMap = f();

For the given code, would the only weakMap item considered as reachable or not? Hence, will it be garbage collected or not?

PS: This question is asked from the perspective of the specification, not particular implementations.

like image 994
zerkms Avatar asked Sep 21 '15 03:09

zerkms


1 Answers

Quoting WeakMap Objects section,

If an object that is being used as the key of a WeakMap key/value pair is only reachable by following a chain of references that start within that WeakMap, then that key/value pair is inaccessible and is automatically removed from the WeakMap.

In your case, the only way to reach o would be to start from one of the keys in the weakMap, as there is no external references to it. So, it would be considered as inaccessible.

WeakMap implementations must detect and remove such key/value pairs and any associated resources.

So, it would be eventually garbage collected.

like image 70
thefourtheye Avatar answered Oct 08 '22 03:10

thefourtheye