-
-
Notifications
You must be signed in to change notification settings - Fork 736
/
Copy pathCancellationTokenSource.java
211 lines (185 loc) · 6.77 KB
/
CancellationTokenSource.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.parse.boltsinternal;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Signals to a {@link CancellationToken} that it should be canceled. To create a {@code
* CancellationToken} first create a {@code CancellationTokenSource} then call {@link #getToken()}
* to retrieve the token for the source.
*
* @see CancellationToken
* @see CancellationTokenSource#getToken()
*/
public class CancellationTokenSource implements Closeable {
private final Object lock = new Object();
private final List<CancellationTokenRegistration> registrations = new ArrayList<>();
private final ScheduledExecutorService executor = BoltsExecutors.scheduled();
private ScheduledFuture<?> scheduledCancellation;
private boolean cancellationRequested;
private boolean closed;
/** Create a new {@code CancellationTokenSource}. */
public CancellationTokenSource() {}
/**
* @return {@code true} if cancellation has been requested for this {@code
* CancellationTokenSource}.
*/
public boolean isCancellationRequested() {
synchronized (lock) {
throwIfClosed();
return cancellationRequested;
}
}
/**
* @return the token that can be passed to asynchronous method to control cancellation.
*/
public CancellationToken getToken() {
synchronized (lock) {
throwIfClosed();
return new CancellationToken(this);
}
}
/** Cancels the token if it has not already been cancelled. */
public void cancel() {
List<CancellationTokenRegistration> registrations;
synchronized (lock) {
throwIfClosed();
if (cancellationRequested) {
return;
}
cancelScheduledCancellation();
cancellationRequested = true;
registrations = new ArrayList<>(this.registrations);
}
notifyListeners(registrations);
}
/**
* Schedules a cancel operation on this {@code CancellationTokenSource} after the specified
* number of milliseconds.
*
* @param delay The number of milliseconds to wait before completing the returned task. If delay
* is {@code 0} the cancel is executed immediately. If delay is {@code -1} any scheduled
* cancellation is stopped.
*/
public void cancelAfter(final long delay) {
cancelAfter(delay, TimeUnit.MILLISECONDS);
}
private void cancelAfter(long delay, TimeUnit timeUnit) {
if (delay < -1) {
throw new IllegalArgumentException("Delay must be >= -1");
}
if (delay == 0) {
cancel();
return;
}
synchronized (lock) {
if (cancellationRequested) {
return;
}
cancelScheduledCancellation();
if (delay != -1) {
scheduledCancellation =
executor.schedule(
() -> {
synchronized (lock) {
scheduledCancellation = null;
}
cancel();
},
delay,
timeUnit);
}
}
}
@Override
public void close() {
synchronized (lock) {
if (closed) {
return;
}
cancelScheduledCancellation();
List<CancellationTokenRegistration> registrations = new ArrayList<>(this.registrations);
for (CancellationTokenRegistration registration : registrations) {
registration.close();
}
this.registrations.clear();
closed = true;
}
}
/* package */ CancellationTokenRegistration register(Runnable action) {
CancellationTokenRegistration ctr;
synchronized (lock) {
throwIfClosed();
ctr = new CancellationTokenRegistration(this, action);
if (cancellationRequested) {
ctr.runAction();
} else {
registrations.add(ctr);
}
}
return ctr;
}
/**
* @throws CancellationException if this token has had cancellation requested. May be used to
* stop execution of a thread or runnable.
*/
/* package */ void throwIfCancellationRequested() throws CancellationException {
synchronized (lock) {
throwIfClosed();
if (cancellationRequested) {
throw new CancellationException();
}
}
}
/* package */ void unregister(CancellationTokenRegistration registration) {
synchronized (lock) {
throwIfClosed();
registrations.remove(registration);
}
}
// This method makes no attempt to perform any synchronization or state checks itself and once
// invoked will notify all runnables unconditionally. As such if you require the notification
// event
// to be synchronized with state changes you should provide external synchronization.
// If this is invoked without external synchronization there is a probability the token becomes
// cancelled concurrently.
private void notifyListeners(List<CancellationTokenRegistration> registrations) {
for (CancellationTokenRegistration registration : registrations) {
registration.runAction();
}
}
@Override
public String toString() {
return String.format(
Locale.US,
"%s@%s[cancellationRequested=%s]",
getClass().getName(),
Integer.toHexString(hashCode()),
isCancellationRequested());
}
// This method makes no attempt to perform any synchronization itself - you should ensure
// accesses to this method are synchronized if you want to ensure correct behaviour in the
// face of a concurrent invocation of the close method.
private void throwIfClosed() {
if (closed) {
throw new IllegalStateException("Object already closed");
}
}
// Performs no synchronization.
private void cancelScheduledCancellation() {
if (scheduledCancellation != null) {
scheduledCancellation.cancel(true);
scheduledCancellation = null;
}
}
}