Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
seleniumhq
GitHub Repository: seleniumhq/selenium
Path: blob/trunk/third_party/closure/goog/async/workqueue.js
4500 views
1
/**
2
* @license
3
* Copyright The Closure Library Authors.
4
* SPDX-License-Identifier: Apache-2.0
5
*/
6
7
goog.module('goog.async.WorkQueue');
8
goog.module.declareLegacyNamespace();
9
10
const FreeList = goog.require('goog.async.FreeList');
11
const {assert} = goog.require('goog.asserts');
12
13
// TODO(johnlenz): generalize the WorkQueue if this is used by more
14
// than goog.async.run.
15
16
17
/**
18
* A low GC workqueue. The key elements of this design:
19
* - avoids the need for goog.bind or equivalent by carrying scope
20
* - avoids the need for array reallocation by using a linked list
21
* - minimizes work entry objects allocation by recycling objects
22
* @final
23
* @struct
24
*/
25
class WorkQueue {
26
constructor() {
27
this.workHead_ = null;
28
this.workTail_ = null;
29
}
30
31
/**
32
* @param {function()} fn
33
* @param {Object|null|undefined} scope
34
*/
35
add(fn, scope) {
36
const item = this.getUnusedItem_();
37
item.set(fn, scope);
38
39
if (this.workTail_) {
40
this.workTail_.next = item;
41
this.workTail_ = item;
42
} else {
43
assert(!this.workHead_);
44
this.workHead_ = item;
45
this.workTail_ = item;
46
}
47
}
48
49
/**
50
* @return {?WorkItem}
51
*/
52
remove() {
53
let item = null;
54
55
if (this.workHead_) {
56
item = this.workHead_;
57
this.workHead_ = this.workHead_.next;
58
if (!this.workHead_) {
59
this.workTail_ = null;
60
}
61
item.next = null;
62
}
63
return item;
64
}
65
66
/**
67
* @param {!WorkItem} item
68
*/
69
returnUnused(item) {
70
WorkQueue.freelist_.put(item);
71
}
72
73
/**
74
* @return {!WorkItem}
75
* @private
76
*/
77
getUnusedItem_() {
78
return WorkQueue.freelist_.get();
79
}
80
}
81
82
/** @define {number} The maximum number of entries to keep for recycling. */
83
WorkQueue.DEFAULT_MAX_UNUSED =
84
goog.define('goog.async.WorkQueue.DEFAULT_MAX_UNUSED', 100);
85
86
/** @const @private {!FreeList<!WorkItem>} */
87
WorkQueue.freelist_ = new FreeList(
88
() => new WorkItem(), item => item.reset(), WorkQueue.DEFAULT_MAX_UNUSED);
89
90
/**
91
* @final
92
* @struct
93
*/
94
class WorkItem {
95
constructor() {
96
/** @type {?function()} */
97
this.fn = null;
98
/** @type {?Object|null|undefined} */
99
this.scope = null;
100
/** @type {?WorkItem} */
101
this.next = null;
102
}
103
104
/**
105
* @param {function()} fn
106
* @param {Object|null|undefined} scope
107
*/
108
set(fn, scope) {
109
this.fn = fn;
110
this.scope = scope;
111
this.next = null;
112
}
113
114
/** Reset the work item so they don't prevent GC before reuse */
115
reset() {
116
this.fn = null;
117
this.scope = null;
118
this.next = null;
119
}
120
}
121
122
exports = WorkQueue;
123
124