Debian Codegraph @

src/main/java/io/reactivex/rxjava3/schedulers/TestScheduler.java

raw
1 /*
2 * Copyright (c) 2016-present, RxJava Contributors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
11 * the License for the specific language governing permissions and limitations under the License.
12 */
13
14 package io.reactivex.rxjava3.schedulers;
15
16 import java.util.Queue;
17 import java.util.concurrent.*;
18 import java.util.concurrent.atomic.AtomicReference;
19
20 import io.reactivex.rxjava3.annotations.*;
21 import io.reactivex.rxjava3.core.Scheduler;
22 import io.reactivex.rxjava3.disposables.Disposable;
23 import io.reactivex.rxjava3.internal.disposables.EmptyDisposable;
24 import io.reactivex.rxjava3.plugins.RxJavaPlugins;
25
26 /**
27 * A special, non thread-safe scheduler for testing operators that require
28 * a scheduler without introducing real concurrency and allows manually advancing
29 * a virtual time.
30 * <p>
31 * By default, the tasks submitted via the various {@code schedule} methods are not
32 * wrapped by the {@link RxJavaPlugins#onSchedule(Runnable)} hook. To enable this behavior,
33 * create a {@code TestScheduler} via {@link #TestScheduler(boolean)} or {@link #TestScheduler(long, TimeUnit, boolean)}.
34 */
35 public final class TestScheduler extends Scheduler {
36 /** The ordered queue for the runnable tasks. */
37 final Queue<TimedRunnable> queue = new PriorityBlockingQueue<>(11);
38 /** Use the {@link RxJavaPlugins#onSchedule(Runnable)} hook when scheduling tasks. */
39 final boolean useOnScheduleHook;
40 /** The per-scheduler global order counter. */
41 long counter;
42 // Storing time in nanoseconds internally.
43 volatile long time;
44
45 /**
46 * Creates a new TestScheduler with initial virtual time of zero.
47 */
48 public TestScheduler() {
49 this(false);
50 }
51
52 /**
53 * Creates a new TestScheduler with the option to use the
54 * {@link RxJavaPlugins#onSchedule(Runnable)} hook when scheduling tasks.
55 * <p>History: 3.0.10 - experimental
56 * @param useOnScheduleHook if {@code true}, the tasks submitted to this
57 * TestScheduler is wrapped via the
58 * {@link RxJavaPlugins#onSchedule(Runnable)} hook
59 * @since 3.1.0
60 */
61 public TestScheduler(boolean useOnScheduleHook) {
62 this.useOnScheduleHook = useOnScheduleHook;
63 }
64
65 /**
66 * Creates a new TestScheduler with the specified initial virtual time.
67 *
68 * @param delayTime
69 * the point in time to move the Scheduler's clock to
70 * @param unit
71 * the units of time that {@code delayTime} is expressed in
72 */
73 public TestScheduler(long delayTime, TimeUnit unit) {
74 this(delayTime, unit, false);
75 }
76
77 /**
78 * Creates a new TestScheduler with the specified initial virtual time
79 * and with the option to use the
80 * {@link RxJavaPlugins#onSchedule(Runnable)} hook when scheduling tasks.
81 * <p>History: 3.0.10 - experimental
82 * @param delayTime
83 * the point in time to move the Scheduler's clock to
84 * @param unit
85 * the units of time that {@code delayTime} is expressed in
86 * @param useOnScheduleHook if {@code true}, the tasks submitted to this
87 * TestScheduler is wrapped via the
88 * {@link RxJavaPlugins#onSchedule(Runnable)} hook
89 * @since 3.1.0
90 */
91 public TestScheduler(long delayTime, TimeUnit unit, boolean useOnScheduleHook) {
92 time = unit.toNanos(delayTime);
93 this.useOnScheduleHook = useOnScheduleHook;
94 }
95
96 static final class TimedRunnable implements Comparable<TimedRunnable> {
97
98 final long time;
99 final Runnable run;
100 final TestWorker scheduler;
101 final long count; // for differentiating tasks at same time
102
103 TimedRunnable(TestWorker scheduler, long time, Runnable run, long count) {
104 this.time = time;
105 this.run = run;
106 this.scheduler = scheduler;
107 this.count = count;
108 }
109
110 @Override
111 public String toString() {
112 return String.format("TimedRunnable(time = %d, run = %s)", time, run.toString());
113 }
114
115 @Override
116 public int compareTo(TimedRunnable o) {
117 if (time == o.time) {
118 return Long.compare(count, o.count);
119 }
120 return Long.compare(time, o.time);
121 }
122 }
123
124 @Override
125 public long now(@NonNull TimeUnit unit) {
126 return unit.convert(time, TimeUnit.NANOSECONDS);
127 }
128
129 /**
130 * Moves the Scheduler's clock forward by a specified amount of time.
131 *
132 * @param delayTime
133 * the amount of time to move the Scheduler's clock forward
134 * @param unit
135 * the units of time that {@code delayTime} is expressed in
136 */
137 public void advanceTimeBy(long delayTime, TimeUnit unit) {
138 advanceTimeTo(time + unit.toNanos(delayTime), TimeUnit.NANOSECONDS);
139 }
140
141 /**
142 * Moves the Scheduler's clock to a particular moment in time.
143 *
144 * @param delayTime
145 * the point in time to move the Scheduler's clock to
146 * @param unit
147 * the units of time that {@code delayTime} is expressed in
148 */
149 public void advanceTimeTo(long delayTime, TimeUnit unit) {
150 long targetTime = unit.toNanos(delayTime);
151 triggerActions(targetTime);
152 }
153
154 /**
155 * Triggers any actions that have not yet been triggered and that are scheduled to be triggered at or
156 * before this Scheduler's present time.
157 */
158 public void triggerActions() {
159 triggerActions(time);
160 }
161
162 private void triggerActions(long targetTimeInNanoseconds) {
163 for (;;) {
164 TimedRunnable current = queue.peek();
165 if (current == null || current.time > targetTimeInNanoseconds) {
166 break;
167 }
168 // if scheduled time is 0 (immediate) use current virtual time
169 time = current.time == 0 ? time : current.time;
170 queue.remove(current);
171
172 // Only execute if not unsubscribed
173 if (!current.scheduler.disposed) {
174 current.run.run();
175 }
176 }
177 time = targetTimeInNanoseconds;
178 }
179
180 @NonNull
181 @Override
182 public Worker createWorker() {
183 return new TestWorker();
184 }
185
186 final class TestWorker extends Worker {
187
188 volatile boolean disposed;
189
190 @Override
191 public void dispose() {
192 disposed = true;
193 }
194
195 @Override
196 public boolean isDisposed() {
197 return disposed;
198 }
199
200 @NonNull
201 @Override
202 public Disposable schedule(@NonNull Runnable run, long delayTime, @NonNull TimeUnit unit) {
203 if (disposed) {
204 return EmptyDisposable.INSTANCE;
205 }
206 if (useOnScheduleHook) {
207 run = RxJavaPlugins.onSchedule(run);
208 }
209 final TimedRunnable timedAction = new TimedRunnable(this, time + unit.toNanos(delayTime), run, counter++);
210 queue.add(timedAction);
211
212 return new QueueRemove(timedAction);
213 }
214
215 @NonNull
216 @Override
217 public Disposable schedule(@NonNull Runnable run) {
218 if (disposed) {
219 return EmptyDisposable.INSTANCE;
220 }
221 if (useOnScheduleHook) {
222 run = RxJavaPlugins.onSchedule(run);
223 }
224 final TimedRunnable timedAction = new TimedRunnable(this, 0, run, counter++);
225 queue.add(timedAction);
226 return new QueueRemove(timedAction);
227 }
228
229 @Override
230 public long now(@NonNull TimeUnit unit) {
231 return TestScheduler.this.now(unit);
232 }
233
234 final class QueueRemove extends AtomicReference<TimedRunnable> implements Disposable {
235
236 private static final long serialVersionUID = -7874968252110604360L;
237
238 QueueRemove(TimedRunnable timedAction) {
239 this.lazySet(timedAction);
240 }
241
242 @Override
243 public void dispose() {
244 TimedRunnable tr = getAndSet(null);
245 if (tr != null) {
246 queue.remove(tr);
247 }
248 }
249
250 @Override
251 public boolean isDisposed() {
252 return get() == null;
253 }
254 }
255 }
256 }