| 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.concurrent.*; |
| 17 |
|
| 18 |
import io.reactivex.rxjava3.annotations.NonNull; |
| 19 |
import io.reactivex.rxjava3.core.Scheduler; |
| 20 |
import io.reactivex.rxjava3.functions.Supplier; |
| 21 |
import io.reactivex.rxjava3.internal.schedulers.*; |
| 22 |
import io.reactivex.rxjava3.plugins.RxJavaPlugins; |
| 23 |
|
| 24 |
/** |
| 25 |
* Static factory methods for returning standard {@link Scheduler} instances. |
| 26 |
* <p> |
| 27 |
* The initial and runtime values of the various scheduler types can be overridden via the |
| 28 |
* {@code RxJavaPlugins.setInit(scheduler name)SchedulerHandler()} and |
| 29 |
* {@code RxJavaPlugins.set(scheduler name)SchedulerHandler()} respectively. |
| 30 |
* Note that overriding any initial {@code Scheduler} via the {@link RxJavaPlugins} |
| 31 |
* has to happen before the {@code Schedulers} class is accessed. |
| 32 |
* <p> |
| 33 |
* <strong>Supported system properties ({@code System.getProperty()}):</strong> |
| 34 |
* <ul> |
| 35 |
* <li>{@code rx3.io-keep-alive-time} (long): sets the keep-alive time of the {@link #io()} {@code Scheduler} workers, default is {@link IoScheduler#KEEP_ALIVE_TIME_DEFAULT}</li> |
| 36 |
* <li>{@code rx3.io-priority} (int): sets the thread priority of the {@link #io()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li> |
| 37 |
* <li>{@code rx3.io-scheduled-release} (boolean): {@code true} sets the worker release mode of the |
| 38 |
* {@link #io()} {@code Scheduler} to <em>scheduled</em>, default is {@code false} for <em>eager</em> mode.</li> |
| 39 |
* <li>{@code rx3.computation-threads} (int): sets the number of threads in the {@link #computation()} {@code Scheduler}, default is the number of available CPUs</li> |
| 40 |
* <li>{@code rx3.computation-priority} (int): sets the thread priority of the {@link #computation()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li> |
| 41 |
* <li>{@code rx3.newthread-priority} (int): sets the thread priority of the {@link #newThread()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li> |
| 42 |
* <li>{@code rx3.single-priority} (int): sets the thread priority of the {@link #single()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li> |
| 43 |
* <li>{@code rx3.purge-enabled} (boolean): enables purging of all {@code Scheduler}'s backing thread pools, default is {@code true}</li> |
| 44 |
* <li>{@code rx3.scheduler.use-nanotime} (boolean): {@code true} instructs {@code Scheduler} to use {@link System#nanoTime()} for {@link Scheduler#now(TimeUnit)}, |
| 45 |
* instead of default {@link System#currentTimeMillis()} ({@code false})</li> |
| 46 |
* </ul> |
| 47 |
*/ |
| 48 |
public final class Schedulers { |
| 49 |
@NonNull |
| 50 |
static final Scheduler SINGLE; |
| 51 |
|
| 52 |
@NonNull |
| 53 |
static final Scheduler COMPUTATION; |
| 54 |
|
| 55 |
@NonNull |
| 56 |
static final Scheduler IO; |
| 57 |
|
| 58 |
@NonNull |
| 59 |
static final Scheduler TRAMPOLINE; |
| 60 |
|
| 61 |
@NonNull |
| 62 |
static final Scheduler NEW_THREAD; |
| 63 |
|
| 64 |
static final class SingleHolder { |
| 65 |
static final Scheduler DEFAULT = new SingleScheduler(); |
| 66 |
} |
| 67 |
|
| 68 |
static final class ComputationHolder { |
| 69 |
static final Scheduler DEFAULT = new ComputationScheduler(); |
| 70 |
} |
| 71 |
|
| 72 |
static final class IoHolder { |
| 73 |
static final Scheduler DEFAULT = new IoScheduler(); |
| 74 |
} |
| 75 |
|
| 76 |
static final class NewThreadHolder { |
| 77 |
static final Scheduler DEFAULT = new NewThreadScheduler(); |
| 78 |
} |
| 79 |
|
| 80 |
static { |
| 81 |
SINGLE = RxJavaPlugins.initSingleScheduler(new SingleTask()); |
| 82 |
|
| 83 |
COMPUTATION = RxJavaPlugins.initComputationScheduler(new ComputationTask()); |
| 84 |
|
| 85 |
IO = RxJavaPlugins.initIoScheduler(new IOTask()); |
| 86 |
|
| 87 |
TRAMPOLINE = TrampolineScheduler.instance(); |
| 88 |
|
| 89 |
NEW_THREAD = RxJavaPlugins.initNewThreadScheduler(new NewThreadTask()); |
| 90 |
} |
| 91 |
|
| 92 |
/** Utility class. */ |
| 93 |
private Schedulers() { |
| 94 |
throw new IllegalStateException("No instances!"); |
| 95 |
} |
| 96 |
|
| 97 |
/** |
| 98 |
* Returns a default, shared {@link Scheduler} instance intended for computational work. |
| 99 |
* <p> |
| 100 |
* This can be used for event-loops, processing callbacks and other computational work. |
| 101 |
* <p> |
| 102 |
* It is not recommended to perform blocking, IO-bound work on this scheduler. Use {@link #io()} instead. |
| 103 |
* <p> |
| 104 |
* The default instance has a backing pool of single-threaded {@link ScheduledExecutorService} instances equal to |
| 105 |
* the number of available processors ({@link java.lang.Runtime#availableProcessors()}) to the Java VM. |
| 106 |
* <p> |
| 107 |
* Unhandled errors will be delivered to the scheduler Thread's {@link java.lang.Thread.UncaughtExceptionHandler}. |
| 108 |
* <p> |
| 109 |
* This type of scheduler is less sensitive to leaking {@link io.reactivex.rxjava3.core.Scheduler.Worker} instances, although |
| 110 |
* not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or |
| 111 |
* execute those tasks "unexpectedly". |
| 112 |
* <p> |
| 113 |
* If the {@link RxJavaPlugins#setFailOnNonBlockingScheduler(boolean)} is set to {@code true}, attempting to execute |
| 114 |
* operators that block while running on this scheduler will throw an {@link IllegalStateException}. |
| 115 |
* <p> |
| 116 |
* You can control certain properties of this standard scheduler via system properties that have to be set |
| 117 |
* before the {@code Schedulers} class is referenced in your code. |
| 118 |
* <p><strong>Supported system properties ({@code System.getProperty()}):</strong> |
| 119 |
* <ul> |
| 120 |
* <li>{@code rx3.computation-threads} (int): sets the number of threads in the {@code computation()} {@code Scheduler}, default is the number of available CPUs</li> |
| 121 |
* <li>{@code rx3.computation-priority} (int): sets the thread priority of the {@code computation()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li> |
| 122 |
* </ul> |
| 123 |
* <p> |
| 124 |
* The default value of this scheduler can be overridden at initialization time via the |
| 125 |
* {@link RxJavaPlugins#setInitComputationSchedulerHandler(io.reactivex.rxjava3.functions.Function)} plugin method. |
| 126 |
* Note that due to possible initialization cycles, using any of the other scheduler-returning methods will |
| 127 |
* result in a {@link NullPointerException}. |
| 128 |
* Once the {@code Schedulers} class has been initialized, you can override the returned {@code Scheduler} instance |
| 129 |
* via the {@link RxJavaPlugins#setComputationSchedulerHandler(io.reactivex.rxjava3.functions.Function)} method. |
| 130 |
* <p> |
| 131 |
* It is possible to create a fresh instance of this scheduler with a custom {@link ThreadFactory}, via the |
| 132 |
* {@link RxJavaPlugins#createComputationScheduler(ThreadFactory)} method. Note that such custom |
| 133 |
* instances require a manual call to {@link Scheduler#shutdown()} to allow the JVM to exit or the |
| 134 |
* (J2EE) container to unload properly. |
| 135 |
* <p>Operators on the base reactive classes that use this scheduler are marked with the |
| 136 |
* @{@link io.reactivex.rxjava3.annotations.SchedulerSupport SchedulerSupport}({@link io.reactivex.rxjava3.annotations.SchedulerSupport#COMPUTATION COMPUTATION}) |
| 137 |
* annotation. |
| 138 |
* @return a {@code Scheduler} meant for computation-bound work |
| 139 |
*/ |
| 140 |
@NonNull |
| 141 |
public static Scheduler computation() { |
| 142 |
return RxJavaPlugins.onComputationScheduler(COMPUTATION); |
| 143 |
} |
| 144 |
|
| 145 |
/** |
| 146 |
* Returns a default, shared {@link Scheduler} instance intended for IO-bound work. |
| 147 |
* <p> |
| 148 |
* This can be used for asynchronously performing blocking IO. |
| 149 |
* <p> |
| 150 |
* The implementation is backed by a pool of single-threaded {@link ScheduledExecutorService} instances |
| 151 |
* that will try to reuse previously started instances used by the worker |
| 152 |
* returned by {@link io.reactivex.rxjava3.core.Scheduler#createWorker()} but otherwise will start a new backing |
| 153 |
* {@link ScheduledExecutorService} instance. Note that this scheduler may create an unbounded number |
| 154 |
* of worker threads that can result in system slowdowns or {@link OutOfMemoryError}. Therefore, for casual uses |
| 155 |
* or when implementing an operator, the Worker instances must be disposed via {@link io.reactivex.rxjava3.core.Scheduler.Worker#dispose()}. |
| 156 |
* <p> |
| 157 |
* It is not recommended to perform computational work on this scheduler. Use {@link #computation()} instead. |
| 158 |
* <p> |
| 159 |
* Unhandled errors will be delivered to the scheduler Thread's {@link java.lang.Thread.UncaughtExceptionHandler}. |
| 160 |
* <p> |
| 161 |
* You can control certain properties of this standard scheduler via system properties that have to be set |
| 162 |
* before the {@code Schedulers} class is referenced in your code. |
| 163 |
* <p><strong>Supported system properties ({@code System.getProperty()}):</strong> |
| 164 |
* <ul> |
| 165 |
* <li>{@code rx3.io-keep-alive-time} (long): sets the keep-alive time of the {@code io()} {@code Scheduler} workers, default is {@link IoScheduler#KEEP_ALIVE_TIME_DEFAULT}</li> |
| 166 |
* <li>{@code rx3.io-priority} (int): sets the thread priority of the {@code io()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li> |
| 167 |
* <li>{@code rx3.io-scheduled-release} (boolean): {@code true} sets the worker release mode of the |
| 168 |
* {@code #io()} {@code Scheduler} to <em>scheduled</em>, default is {@code false} for <em>eager</em> mode.</li> |
| 169 |
* </ul> |
| 170 |
* <p> |
| 171 |
* The default value of this scheduler can be overridden at initialization time via the |
| 172 |
* {@link RxJavaPlugins#setInitIoSchedulerHandler(io.reactivex.rxjava3.functions.Function)} plugin method. |
| 173 |
* Note that due to possible initialization cycles, using any of the other scheduler-returning methods will |
| 174 |
* result in a {@link NullPointerException}. |
| 175 |
* Once the {@code Schedulers} class has been initialized, you can override the returned {@code Scheduler} instance |
| 176 |
* via the {@link RxJavaPlugins#setIoSchedulerHandler(io.reactivex.rxjava3.functions.Function)} method. |
| 177 |
* <p> |
| 178 |
* It is possible to create a fresh instance of this scheduler with a custom {@link ThreadFactory}, via the |
| 179 |
* {@link RxJavaPlugins#createIoScheduler(ThreadFactory)} method. Note that such custom |
| 180 |
* instances require a manual call to {@link Scheduler#shutdown()} to allow the JVM to exit or the |
| 181 |
* (J2EE) container to unload properly. |
| 182 |
* <p>Operators on the base reactive classes that use this scheduler are marked with the |
| 183 |
* @{@link io.reactivex.rxjava3.annotations.SchedulerSupport SchedulerSupport}({@link io.reactivex.rxjava3.annotations.SchedulerSupport#IO IO}) |
| 184 |
* annotation. |
| 185 |
* <p> |
| 186 |
* When the {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} is disposed, |
| 187 |
* the underlying worker can be released to the cached worker pool in two modes: |
| 188 |
* <ul> |
| 189 |
* <li>In <em>eager</em> mode (default), the underlying worker is returned immediately to the cached worker pool |
| 190 |
* and can be reused much quicker by operators. The drawback is that if the currently running task doesn't |
| 191 |
* respond to interruption in time or at all, this may lead to delays or deadlock with the reuse use of the |
| 192 |
* underlying worker. |
| 193 |
* </li> |
| 194 |
* <li>In <em>scheduled</em> mode (enabled via the system parameter {@code rx3.io-scheduled-release} |
| 195 |
* set to {@code true}), the underlying worker is returned to the cached worker pool only after the currently running task |
| 196 |
* has finished. This can help prevent premature reuse of the underlying worker and likely won't lead to delays or |
| 197 |
* deadlock with such reuses. The drawback is that the delay in release may lead to an excess amount of underlying |
| 198 |
* workers being created. |
| 199 |
* </li> |
| 200 |
* </ul> |
| 201 |
* @return a {@code Scheduler} meant for IO-bound work |
| 202 |
*/ |
| 203 |
@NonNull |
| 204 |
public static Scheduler io() { |
| 205 |
return RxJavaPlugins.onIoScheduler(IO); |
| 206 |
} |
| 207 |
|
| 208 |
/** |
| 209 |
* Returns a default, shared {@link Scheduler} instance whose {@link io.reactivex.rxjava3.core.Scheduler.Worker} |
| 210 |
* instances queue work and execute them in a FIFO manner on one of the participating threads. |
| 211 |
* <p> |
| 212 |
* The default implementation's {@link Scheduler#scheduleDirect(Runnable)} methods execute the tasks on the current thread |
| 213 |
* without any queueing and the timed overloads use blocking sleep as well. |
| 214 |
* <p> |
| 215 |
* Note that this scheduler can't be reliably used to return the execution of |
| 216 |
* tasks to the "main" thread. Such behavior requires a blocking-queueing scheduler currently not provided |
| 217 |
* by RxJava itself but may be found in external libraries. |
| 218 |
* <p> |
| 219 |
* This scheduler can't be overridden via an {@link RxJavaPlugins} method. |
| 220 |
* @return a {@code Scheduler} that queues work on the current thread |
| 221 |
*/ |
| 222 |
@NonNull |
| 223 |
public static Scheduler trampoline() { |
| 224 |
return TRAMPOLINE; |
| 225 |
} |
| 226 |
|
| 227 |
/** |
| 228 |
* Returns a default, shared {@link Scheduler} instance that creates a new {@link Thread} for each unit of work. |
| 229 |
* <p> |
| 230 |
* The default implementation of this scheduler creates a new, single-threaded {@link ScheduledExecutorService} for |
| 231 |
* each invocation of the {@link Scheduler#scheduleDirect(Runnable)} (plus its overloads) and {@link Scheduler#createWorker()} |
| 232 |
* methods, thus an unbounded number of worker threads may be created that can |
| 233 |
* result in system slowdowns or {@link OutOfMemoryError}. Therefore, for casual uses or when implementing an operator, |
| 234 |
* the Worker instances must be disposed via {@link io.reactivex.rxjava3.core.Scheduler.Worker#dispose()}. |
| 235 |
* <p> |
| 236 |
* Unhandled errors will be delivered to the scheduler Thread's {@link java.lang.Thread.UncaughtExceptionHandler}. |
| 237 |
* <p> |
| 238 |
* You can control certain properties of this standard scheduler via system properties that have to be set |
| 239 |
* before the {@code Schedulers} class is referenced in your code. |
| 240 |
* <p><strong>Supported system properties ({@code System.getProperty()}):</strong> |
| 241 |
* <ul> |
| 242 |
* <li>{@code rx3.newthread-priority} (int): sets the thread priority of the {@code newThread()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li> |
| 243 |
* </ul> |
| 244 |
* <p> |
| 245 |
* The default value of this scheduler can be overridden at initialization time via the |
| 246 |
* {@link RxJavaPlugins#setInitNewThreadSchedulerHandler(io.reactivex.rxjava3.functions.Function)} plugin method. |
| 247 |
* Note that due to possible initialization cycles, using any of the other scheduler-returning methods will |
| 248 |
* result in a {@link NullPointerException}. |
| 249 |
* Once the {@code Schedulers} class has been initialized, you can override the returned {@code Scheduler} instance |
| 250 |
* via the {@link RxJavaPlugins#setNewThreadSchedulerHandler(io.reactivex.rxjava3.functions.Function)} method. |
| 251 |
* <p> |
| 252 |
* It is possible to create a fresh instance of this scheduler with a custom {@link ThreadFactory}, via the |
| 253 |
* {@link RxJavaPlugins#createNewThreadScheduler(ThreadFactory)} method. Note that such custom |
| 254 |
* instances require a manual call to {@link Scheduler#shutdown()} to allow the JVM to exit or the |
| 255 |
* (J2EE) container to unload properly. |
| 256 |
* <p>Operators on the base reactive classes that use this scheduler are marked with the |
| 257 |
* @{@link io.reactivex.rxjava3.annotations.SchedulerSupport SchedulerSupport}({@link io.reactivex.rxjava3.annotations.SchedulerSupport#NEW_THREAD NEW_TRHEAD}) |
| 258 |
* annotation. |
| 259 |
* @return a {@code Scheduler} that creates new threads |
| 260 |
*/ |
| 261 |
@NonNull |
| 262 |
public static Scheduler newThread() { |
| 263 |
return RxJavaPlugins.onNewThreadScheduler(NEW_THREAD); |
| 264 |
} |
| 265 |
|
| 266 |
/** |
| 267 |
* Returns a default, shared, single-thread-backed {@link Scheduler} instance for work |
| 268 |
* requiring strongly-sequential execution on the same background thread. |
| 269 |
* <p> |
| 270 |
* Uses: |
| 271 |
* <ul> |
| 272 |
* <li>event loop</li> |
| 273 |
* <li>support {@code Schedulers.from(}{@link Executor}{@code )} and {@code from(}{@link ExecutorService}{@code )} with delayed scheduling</li> |
| 274 |
* <li>support benchmarks that pipeline data from some thread to another thread and |
| 275 |
* avoid core-bashing of computation's round-robin nature</li> |
| 276 |
* </ul> |
| 277 |
* <p> |
| 278 |
* Unhandled errors will be delivered to the scheduler Thread's {@link java.lang.Thread.UncaughtExceptionHandler}. |
| 279 |
* <p> |
| 280 |
* This type of scheduler is less sensitive to leaking {@link io.reactivex.rxjava3.core.Scheduler.Worker} instances, although |
| 281 |
* not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or |
| 282 |
* execute those tasks "unexpectedly". |
| 283 |
* <p> |
| 284 |
* If the {@link RxJavaPlugins#setFailOnNonBlockingScheduler(boolean)} is set to {@code true}, attempting to execute |
| 285 |
* operators that block while running on this scheduler will throw an {@link IllegalStateException}. |
| 286 |
* <p> |
| 287 |
* You can control certain properties of this standard scheduler via system properties that have to be set |
| 288 |
* before the {@code Schedulers} class is referenced in your code. |
| 289 |
* <p><strong>Supported system properties ({@code System.getProperty()}):</strong> |
| 290 |
* <ul> |
| 291 |
* <li>{@code rx3.single-priority} (int): sets the thread priority of the {@code single()} {@code Scheduler}, default is {@link Thread#NORM_PRIORITY}</li> |
| 292 |
* </ul> |
| 293 |
* <p> |
| 294 |
* The default value of this scheduler can be overridden at initialization time via the |
| 295 |
* {@link RxJavaPlugins#setInitSingleSchedulerHandler(io.reactivex.rxjava3.functions.Function)} plugin method. |
| 296 |
* Note that due to possible initialization cycles, using any of the other scheduler-returning methods will |
| 297 |
* result in a {@link NullPointerException}. |
| 298 |
* Once the {@code Schedulers} class has been initialized, you can override the returned {@code Scheduler} instance |
| 299 |
* via the {@link RxJavaPlugins#setSingleSchedulerHandler(io.reactivex.rxjava3.functions.Function)} method. |
| 300 |
* <p> |
| 301 |
* It is possible to create a fresh instance of this scheduler with a custom {@link ThreadFactory}, via the |
| 302 |
* {@link RxJavaPlugins#createSingleScheduler(ThreadFactory)} method. Note that such custom |
| 303 |
* instances require a manual call to {@link Scheduler#shutdown()} to allow the JVM to exit or the |
| 304 |
* (J2EE) container to unload properly. |
| 305 |
* <p>Operators on the base reactive classes that use this scheduler are marked with the |
| 306 |
* @{@link io.reactivex.rxjava3.annotations.SchedulerSupport SchedulerSupport}({@link io.reactivex.rxjava3.annotations.SchedulerSupport#SINGLE SINGLE}) |
| 307 |
* annotation. |
| 308 |
* @return a {@code Scheduler} that shares a single backing thread. |
| 309 |
* @since 2.0 |
| 310 |
*/ |
| 311 |
@NonNull |
| 312 |
public static Scheduler single() { |
| 313 |
return RxJavaPlugins.onSingleScheduler(SINGLE); |
| 314 |
} |
| 315 |
|
| 316 |
/** |
| 317 |
* Wraps an {@link Executor} into a new {@link Scheduler} instance and delegates {@code schedule()} |
| 318 |
* calls to it. |
| 319 |
* <p> |
| 320 |
* If the provided executor doesn't support any of the more specific standard Java executor |
| 321 |
* APIs, cancelling tasks scheduled by this scheduler can't be interrupted when they are |
| 322 |
* executing but only prevented from running prior to that. In addition, tasks scheduled with |
| 323 |
* a time delay or periodically will use the {@link #single()} scheduler for the timed waiting |
| 324 |
* before posting the actual task to the given executor. |
| 325 |
* <p> |
| 326 |
* Tasks submitted to the {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} of this {@code Scheduler} are also not interruptible. Use the |
| 327 |
* {@link #from(Executor, boolean)} overload to enable task interruption via this wrapper. |
| 328 |
* <p> |
| 329 |
* If the provided executor supports the standard Java {@link ExecutorService} API, |
| 330 |
* cancelling tasks scheduled by this scheduler can be cancelled/interrupted by calling |
| 331 |
* {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with |
| 332 |
* a time delay or periodically will use the {@link #single()} scheduler for the timed waiting |
| 333 |
* before posting the actual task to the given executor. |
| 334 |
* <p> |
| 335 |
* If the provided executor supports the standard Java {@link ScheduledExecutorService} API, |
| 336 |
* cancelling tasks scheduled by this scheduler can be cancelled/interrupted by calling |
| 337 |
* {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with |
| 338 |
* a time delay or periodically will use the provided executor. Note, however, if the provided |
| 339 |
* {@code ScheduledExecutorService} instance is not single threaded, tasks scheduled |
| 340 |
* with a time delay close to each other may end up executing in different order than |
| 341 |
* the original schedule() call was issued. This limitation may be lifted in a future patch. |
| 342 |
* <p> |
| 343 |
* The implementation of the Worker of this wrapper {@code Scheduler} is eager and will execute as many |
| 344 |
* non-delayed tasks as it can, which may result in a longer than expected occupation of a |
| 345 |
* thread of the given backing {@code Executor}. In other terms, it does not allow per-{@link Runnable} fairness |
| 346 |
* in case the worker runs on a shared underlying thread of the {@code Executor}. |
| 347 |
* See {@link #from(Executor, boolean, boolean)} to create a wrapper that uses the underlying {@code Executor} |
| 348 |
* more fairly. |
| 349 |
* <p> |
| 350 |
* Starting, stopping and restarting this scheduler is not supported (no-op) and the provided |
| 351 |
* executor's lifecycle must be managed externally: |
| 352 |
* <pre><code> |
| 353 |
* ExecutorService exec = Executors.newSingleThreadedExecutor(); |
| 354 |
* try { |
| 355 |
* Scheduler scheduler = Schedulers.from(exec); |
| 356 |
* Flowable.just(1) |
| 357 |
* .subscribeOn(scheduler) |
| 358 |
* .map(v -> v + 1) |
| 359 |
* .observeOn(scheduler) |
| 360 |
* .blockingSubscribe(System.out::println); |
| 361 |
* } finally { |
| 362 |
* exec.shutdown(); |
| 363 |
* } |
| 364 |
* </code></pre> |
| 365 |
* <p> |
| 366 |
* Note that the provided {@code Executor} should avoid throwing a {@link RejectedExecutionException} |
| 367 |
* (for example, by shutting it down prematurely or using a bounded-queue {@code ExecutorService}) |
| 368 |
* because such circumstances prevent RxJava from progressing flow-related activities correctly. |
| 369 |
* If the {@link Executor#execute(Runnable)} or {@link ExecutorService#submit(Callable)} throws, |
| 370 |
* the {@code RejectedExecutionException} is routed to the global error handler via |
| 371 |
* {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-related problems, it is recommended |
| 372 |
* all flows using the returned {@code Scheduler} to be canceled/disposed before the underlying |
| 373 |
* {@code Executor} is shut down. To avoid problems due to the {@code Executor} having a bounded-queue, |
| 374 |
* it is recommended to rephrase the flow to utilize backpressure as the means to limit outstanding work. |
| 375 |
* <p> |
| 376 |
* This type of scheduler is less sensitive to leaking {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} instances, although |
| 377 |
* not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or |
| 378 |
* execute those tasks "unexpectedly". |
| 379 |
* <p> |
| 380 |
* Note that this method returns a new {@code Scheduler} instance, even for the same {@code Executor} instance. |
| 381 |
* <p> |
| 382 |
* It is possible to wrap an {@code Executor} into a {@code Scheduler} without triggering the initialization of all the |
| 383 |
* standard schedulers by using the {@link RxJavaPlugins#createExecutorScheduler(Executor, boolean, boolean)} method |
| 384 |
* before the {@code Schedulers} class itself is accessed. |
| 385 |
* @param executor |
| 386 |
* the executor to wrap |
| 387 |
* @return the new {@code Scheduler} wrapping the {@code Executor} |
| 388 |
* @see #from(Executor, boolean, boolean) |
| 389 |
*/ |
| 390 |
@NonNull |
| 391 |
public static Scheduler from(@NonNull Executor executor) { |
| 392 |
return from(executor, false, false); |
| 393 |
} |
| 394 |
|
| 395 |
/** |
| 396 |
* Wraps an {@link Executor} into a new {@link Scheduler} instance and delegates {@code schedule()} |
| 397 |
* calls to it. |
| 398 |
* <p> |
| 399 |
* The tasks scheduled by the returned {@code Scheduler} and its {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} |
| 400 |
* can be optionally interrupted. |
| 401 |
* <p> |
| 402 |
* If the provided executor doesn't support any of the more specific standard Java executor |
| 403 |
* APIs, tasks scheduled with a time delay or periodically will use the |
| 404 |
* {@link #single()} scheduler for the timed waiting |
| 405 |
* before posting the actual task to the given executor. |
| 406 |
* <p> |
| 407 |
* If the provided executor supports the standard Java {@link ExecutorService} API, |
| 408 |
* canceling tasks scheduled by this scheduler can be cancelled/interrupted by calling |
| 409 |
* {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with |
| 410 |
* a time delay or periodically will use the {@link #single()} scheduler for the timed waiting |
| 411 |
* before posting the actual task to the given executor. |
| 412 |
* <p> |
| 413 |
* If the provided executor supports the standard Java {@link ScheduledExecutorService} API, |
| 414 |
* canceling tasks scheduled by this scheduler can be cancelled/interrupted by calling |
| 415 |
* {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with |
| 416 |
* a time delay or periodically will use the provided executor. Note, however, if the provided |
| 417 |
* {@code ScheduledExecutorService} instance is not single threaded, tasks scheduled |
| 418 |
* with a time delay close to each other may end up executing in different order than |
| 419 |
* the original schedule() call was issued. This limitation may be lifted in a future patch. |
| 420 |
* <p> |
| 421 |
* The implementation of the {@code Worker} of this wrapper {@code Scheduler} is eager and will execute as many |
| 422 |
* non-delayed tasks as it can, which may result in a longer than expected occupation of a |
| 423 |
* thread of the given backing {@code Executor}. In other terms, it does not allow per-{@link Runnable} fairness |
| 424 |
* in case the worker runs on a shared underlying thread of the {@code Executor}. |
| 425 |
* See {@link #from(Executor, boolean, boolean)} to create a wrapper that uses the underlying {@code Executor} |
| 426 |
* more fairly. |
| 427 |
* <p> |
| 428 |
* Starting, stopping and restarting this scheduler is not supported (no-op) and the provided |
| 429 |
* executor's lifecycle must be managed externally: |
| 430 |
* <pre><code> |
| 431 |
* ExecutorService exec = Executors.newSingleThreadedExecutor(); |
| 432 |
* try { |
| 433 |
* Scheduler scheduler = Schedulers.from(exec, true); |
| 434 |
* Flowable.just(1) |
| 435 |
* .subscribeOn(scheduler) |
| 436 |
* .map(v -> v + 1) |
| 437 |
* .observeOn(scheduler) |
| 438 |
* .blockingSubscribe(System.out::println); |
| 439 |
* } finally { |
| 440 |
* exec.shutdown(); |
| 441 |
* } |
| 442 |
* </code></pre> |
| 443 |
* <p> |
| 444 |
* Note that the provided {@code Executor} should avoid throwing a {@link RejectedExecutionException} |
| 445 |
* (for example, by shutting it down prematurely or using a bounded-queue {@code ExecutorService}) |
| 446 |
* because such circumstances prevent RxJava from progressing flow-related activities correctly. |
| 447 |
* If the {@link Executor#execute(Runnable)} or {@link ExecutorService#submit(Callable)} throws, |
| 448 |
* the {@code RejectedExecutionException} is routed to the global error handler via |
| 449 |
* {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-related problems, it is recommended |
| 450 |
* all flows using the returned {@code Scheduler} to be canceled/disposed before the underlying |
| 451 |
* {@code Executor} is shut down. To avoid problems due to the {@code Executor} having a bounded-queue, |
| 452 |
* it is recommended to rephrase the flow to utilize backpressure as the means to limit outstanding work. |
| 453 |
* <p> |
| 454 |
* This type of scheduler is less sensitive to leaking {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} instances, although |
| 455 |
* not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or |
| 456 |
* execute those tasks "unexpectedly". |
| 457 |
* <p> |
| 458 |
* Note that this method returns a new {@code Scheduler} instance, even for the same {@code Executor} instance. |
| 459 |
* <p> |
| 460 |
* It is possible to wrap an {@code Executor} into a {@code Scheduler} without triggering the initialization of all the |
| 461 |
* standard schedulers by using the {@link RxJavaPlugins#createExecutorScheduler(Executor, boolean, boolean)} method |
| 462 |
* before the {@code Schedulers} class itself is accessed. |
| 463 |
* <p>History: 2.2.6 - experimental |
| 464 |
* @param executor |
| 465 |
* the executor to wrap |
| 466 |
* @param interruptibleWorker if {@code true}, the tasks submitted to the {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} will |
| 467 |
* be interrupted when the task is disposed. |
| 468 |
* @return the new {@code Scheduler} wrapping the {@code Executor} |
| 469 |
* @since 3.0.0 |
| 470 |
* @see #from(Executor, boolean, boolean) |
| 471 |
*/ |
| 472 |
@NonNull |
| 473 |
public static Scheduler from(@NonNull Executor executor, boolean interruptibleWorker) { |
| 474 |
return from(executor, interruptibleWorker, false); |
| 475 |
} |
| 476 |
|
| 477 |
/** |
| 478 |
* Wraps an {@link Executor} into a new {@link Scheduler} instance and delegates {@code schedule()} |
| 479 |
* calls to it. |
| 480 |
* <p> |
| 481 |
* The tasks scheduled by the returned {@code Scheduler} and its {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} |
| 482 |
* can be optionally interrupted. |
| 483 |
* <p> |
| 484 |
* If the provided executor doesn't support any of the more specific standard Java executor |
| 485 |
* APIs, tasks scheduled with a time delay or periodically will use the |
| 486 |
* {@link #single()} scheduler for the timed waiting |
| 487 |
* before posting the actual task to the given executor. |
| 488 |
* <p> |
| 489 |
* If the provided executor supports the standard Java {@link ExecutorService} API, |
| 490 |
* canceling tasks scheduled by this scheduler can be cancelled/interrupted by calling |
| 491 |
* {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with |
| 492 |
* a time delay or periodically will use the {@link #single()} scheduler for the timed waiting |
| 493 |
* before posting the actual task to the given executor. |
| 494 |
* <p> |
| 495 |
* If the provided executor supports the standard Java {@link ScheduledExecutorService} API, |
| 496 |
* canceling tasks scheduled by this scheduler can be cancelled/interrupted by calling |
| 497 |
* {@link io.reactivex.rxjava3.disposables.Disposable#dispose()}. In addition, tasks scheduled with |
| 498 |
* a time delay or periodically will use the provided executor. Note, however, if the provided |
| 499 |
* {@code ScheduledExecutorService} instance is not single threaded, tasks scheduled |
| 500 |
* with a time delay close to each other may end up executing in different order than |
| 501 |
* the original schedule() call was issued. This limitation may be lifted in a future patch. |
| 502 |
* <p> |
| 503 |
* The implementation of the Worker of this wrapper {@code Scheduler} can operate in both eager (non-fair) and |
| 504 |
* fair modes depending on the specified parameter. In <em>eager</em> mode, it will execute as many |
| 505 |
* non-delayed tasks as it can, which may result in a longer than expected occupation of a |
| 506 |
* thread of the given backing {@code Executor}. In other terms, it does not allow per-{@link Runnable} fairness |
| 507 |
* in case the worker runs on a shared underlying thread of the {@code Executor}. In <em>fair</em> mode, |
| 508 |
* non-delayed tasks will still be executed in a FIFO and non-overlapping manner, but after each task, |
| 509 |
* the execution for the next task is rescheduled with the same underlying {@code Executor}, allowing interleaving |
| 510 |
* from both the same {@code Scheduler} or other external usages of the underlying {@code Executor}. |
| 511 |
* <p> |
| 512 |
* Starting, stopping and restarting this scheduler is not supported (no-op) and the provided |
| 513 |
* executor's lifecycle must be managed externally: |
| 514 |
* <pre><code> |
| 515 |
* ExecutorService exec = Executors.newSingleThreadedExecutor(); |
| 516 |
* try { |
| 517 |
* Scheduler scheduler = Schedulers.from(exec, true, true); |
| 518 |
* Flowable.just(1) |
| 519 |
* .subscribeOn(scheduler) |
| 520 |
* .map(v -> v + 1) |
| 521 |
* .observeOn(scheduler) |
| 522 |
* .blockingSubscribe(System.out::println); |
| 523 |
* } finally { |
| 524 |
* exec.shutdown(); |
| 525 |
* } |
| 526 |
* </code></pre> |
| 527 |
* <p> |
| 528 |
* Note that the provided {@code Executor} should avoid throwing a {@link RejectedExecutionException} |
| 529 |
* (for example, by shutting it down prematurely or using a bounded-queue {@code ExecutorService}) |
| 530 |
* because such circumstances prevent RxJava from progressing flow-related activities correctly. |
| 531 |
* If the {@link Executor#execute(Runnable)} or {@link ExecutorService#submit(Callable)} throws, |
| 532 |
* the {@code RejectedExecutionException} is routed to the global error handler via |
| 533 |
* {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-related problems, it is recommended |
| 534 |
* all flows using the returned {@code Scheduler} to be canceled/disposed before the underlying |
| 535 |
* {@code Executor} is shut down. To avoid problems due to the {@code Executor} having a bounded-queue, |
| 536 |
* it is recommended to rephrase the flow to utilize backpressure as the means to limit outstanding work. |
| 537 |
* <p> |
| 538 |
* This type of scheduler is less sensitive to leaking {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} instances, although |
| 539 |
* not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or |
| 540 |
* execute those tasks "unexpectedly". |
| 541 |
* <p> |
| 542 |
* Note that this method returns a new {@code Scheduler} instance, even for the same {@code Executor} instance. |
| 543 |
* <p> |
| 544 |
* It is possible to wrap an {@code Executor} into a {@code Scheduler} without triggering the initialization of all the |
| 545 |
* standard schedulers by using the {@link RxJavaPlugins#createExecutorScheduler(Executor, boolean, boolean)} method |
| 546 |
* before the {@code Schedulers} class itself is accessed. |
| 547 |
* |
| 548 |
* @param executor |
| 549 |
* the executor to wrap |
| 550 |
* @param interruptibleWorker if {@code true}, the tasks submitted to the {@link io.reactivex.rxjava3.core.Scheduler.Worker Scheduler.Worker} will |
| 551 |
* be interrupted when the task is disposed. |
| 552 |
* @param fair if {@code true}, tasks submitted to the {@code Scheduler} or {@code Worker} will be executed by the underlying {@code Executor} one after the other, still |
| 553 |
* in a FIFO and non-overlapping manner, but allows interleaving with other tasks submitted to the underlying {@code Executor}. |
| 554 |
* If {@code false}, the underlying FIFO scheme will execute as many tasks as it can before giving up the underlying {@code Executor} thread. |
| 555 |
* @return the new {@code Scheduler} wrapping the {@code Executor} |
| 556 |
* @since 3.0.0 |
| 557 |
*/ |
| 558 |
@NonNull |
| 559 |
public static Scheduler from(@NonNull Executor executor, boolean interruptibleWorker, boolean fair) { |
| 560 |
return RxJavaPlugins.createExecutorScheduler(executor, interruptibleWorker, fair); |
| 561 |
} |
| 562 |
|
| 563 |
/** |
| 564 |
* Shuts down the standard {@link Scheduler}s. |
| 565 |
* <p>The operation is idempotent and thread-safe. |
| 566 |
*/ |
| 567 |
public static void shutdown() { |
| 568 |
computation().shutdown(); |
| 569 |
io().shutdown(); |
| 570 |
newThread().shutdown(); |
| 571 |
single().shutdown(); |
| 572 |
trampoline().shutdown(); |
| 573 |
} |
| 574 |
|
| 575 |
/** |
| 576 |
* Starts the standard {@link Scheduler}s. |
| 577 |
* <p>The operation is idempotent and thread-safe. |
| 578 |
*/ |
| 579 |
public static void start() { |
| 580 |
computation().start(); |
| 581 |
io().start(); |
| 582 |
newThread().start(); |
| 583 |
single().start(); |
| 584 |
trampoline().start(); |
| 585 |
} |
| 586 |
|
| 587 |
static final class IOTask implements Supplier<Scheduler> { |
| 588 |
@Override |
| 589 |
public Scheduler get() { |
| 590 |
return IoHolder.DEFAULT; |
| 591 |
} |
| 592 |
} |
| 593 |
|
| 594 |
static final class NewThreadTask implements Supplier<Scheduler> { |
| 595 |
@Override |
| 596 |
public Scheduler get() { |
| 597 |
return NewThreadHolder.DEFAULT; |
| 598 |
} |
| 599 |
} |
| 600 |
|
| 601 |
static final class SingleTask implements Supplier<Scheduler> { |
| 602 |
@Override |
| 603 |
public Scheduler get() { |
| 604 |
return SingleHolder.DEFAULT; |
| 605 |
} |
| 606 |
} |
| 607 |
|
| 608 |
static final class ComputationTask implements Supplier<Scheduler> { |
| 609 |
@Override |
| 610 |
public Scheduler get() { |
| 611 |
return ComputationHolder.DEFAULT; |
| 612 |
} |
| 613 |
} |
| 614 |
} |