maybe-garbage-collect.js (1759B)
1 /** 2 * maybeGarbageCollectAsync 3 * 4 * It might garbage collect, it might not. If it doesn't, that's ok. 5 */ 6 self.maybeGarbageCollectAsync = garbageCollect; 7 8 /** 9 * maybeGarbageCollectKeptObjectsAsync 10 * 11 * Based on "asyncGCDeref" in https://github.com/tc39/test262/blob/master/harness/async-gc.js 12 * 13 * @return {Promise} Resolves to a trigger if ClearKeptObjects 14 * exists to provide one 15 */ 16 async function maybeGarbageCollectKeptObjectsAsync() { 17 let trigger; 18 19 if (typeof ClearKeptObjects === 'function') { 20 trigger = ClearKeptObjects(); 21 } 22 23 await maybeGarbageCollectAsync(); 24 25 return trigger; 26 } 27 28 /** 29 * maybeGarbageCollectAndCleanupAsync 30 * 31 * Based on "asyncGC" in https://github.com/tc39/test262/blob/master/harness/async-gc.js 32 * 33 * @return {undefined} 34 */ 35 async function maybeGarbageCollectAndCleanupAsync(...targets) { 36 let finalizationRegistry = new FinalizationRegistry(() => {}); 37 let length = targets.length; 38 39 for (let target of targets) { 40 finalizationRegistry.register(target, 'target'); 41 target = null; 42 } 43 44 targets = null; 45 46 await 'tick'; 47 await maybeGarbageCollectKeptObjectsAsync(); 48 49 let names = []; 50 51 finalizationRegistry.cleanupSome(name => names.push(name)); 52 53 if (names.length !== length) { 54 throw maybeGarbageCollectAndCleanupAsync.NOT_COLLECTED; 55 } 56 } 57 58 maybeGarbageCollectAndCleanupAsync.NOT_COLLECTED = Symbol('Object was not collected'); 59 60 /** 61 * resolveGarbageCollection 62 * 63 * Based on "resolveAsyncGC" in https://github.com/tc39/test262/blob/master/harness/async-gc.js 64 * 65 * @param {Error} error An error object. 66 * @return {undefined} 67 */ 68 function resolveGarbageCollection(error) { 69 if (error && error !== maybeGarbageCollectAndCleanupAsync.NOT_COLLECTED) { 70 throw error; 71 } 72 }