-
Notifications
You must be signed in to change notification settings - Fork 3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(asapScheduler): resolved memory leak (#5183)
Registered handlers would sometimes leak in memory, this resolves that issue and adds a test. Related #5016
- Loading branch information
Showing
2 changed files
with
40 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,41 @@ | ||
let nextHandle = 1; | ||
const RESOLVED = (() => Promise.resolve())(); | ||
const activeHandles: { [key: number]: any } = {}; | ||
|
||
const tasksByHandle: { [handle: string]: () => void } = {}; | ||
|
||
function runIfPresent(handle: number) { | ||
const cb = tasksByHandle[handle]; | ||
if (cb) { | ||
cb(); | ||
/** | ||
* Finds the handle in the list of active handles, and removes it. | ||
* Returns `true` if found, `false` otherwise. Used both to clear | ||
* Immediate scheduled tasks, and to identify if a task should be scheduled. | ||
*/ | ||
function findAndClearHandle(handle: number): boolean { | ||
if (handle in activeHandles) { | ||
delete activeHandles[handle]; | ||
return true; | ||
} | ||
return false; | ||
} | ||
|
||
/** | ||
* Helper functions to schedule and unschedule microtasks. | ||
*/ | ||
export const Immediate = { | ||
setImmediate(cb: () => void): number { | ||
const handle = nextHandle++; | ||
tasksByHandle[handle] = cb; | ||
Promise.resolve().then(() => runIfPresent(handle)); | ||
activeHandles[handle] = true; | ||
RESOLVED.then(() => findAndClearHandle(handle) && cb()); | ||
return handle; | ||
}, | ||
|
||
clearImmediate(handle: number): void { | ||
delete tasksByHandle[handle]; | ||
findAndClearHandle(handle); | ||
}, | ||
}; | ||
|
||
/** | ||
* Used for internal testing purposes only. Do not export from library. | ||
*/ | ||
export const TestTools = { | ||
pending() { | ||
return Object.keys(activeHandles).length; | ||
} | ||
}; |