Debian Codegraph @

src/main/java/io/reactivex/rxjava3/internal/schedulers/IoScheduler.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.internal.schedulers;
15
16 import java.util.concurrent.*;
17 import java.util.concurrent.atomic.*;
18
19 import io.reactivex.rxjava3.annotations.NonNull;
20 import io.reactivex.rxjava3.core.Scheduler;
21 import io.reactivex.rxjava3.disposables.*;
22 import io.reactivex.rxjava3.internal.disposables.EmptyDisposable;
23
24 /**
25 * Scheduler that creates and caches a set of thread pools and reuses them if possible.
26 */
27 public final class IoScheduler extends Scheduler {
28 private static final String WORKER_THREAD_NAME_PREFIX = "RxCachedThreadScheduler";
29 static final RxThreadFactory WORKER_THREAD_FACTORY;
30
31 private static final String EVICTOR_THREAD_NAME_PREFIX = "RxCachedWorkerPoolEvictor";
32 static final RxThreadFactory EVICTOR_THREAD_FACTORY;
33
34 /** The name of the system property for setting the keep-alive time (in seconds) for this Scheduler workers. */
35 private static final String KEY_KEEP_ALIVE_TIME = "rx3.io-keep-alive-time";
36 public static final long KEEP_ALIVE_TIME_DEFAULT = 60;
37
38 private static final long KEEP_ALIVE_TIME;
39 private static final TimeUnit KEEP_ALIVE_UNIT = TimeUnit.SECONDS;
40
41 static final ThreadWorker SHUTDOWN_THREAD_WORKER;
42 final ThreadFactory threadFactory;
43 final AtomicReference<CachedWorkerPool> pool;
44
45 /** The name of the system property for setting the thread priority for this Scheduler. */
46 private static final String KEY_IO_PRIORITY = "rx3.io-priority";
47
48 /** The name of the system property for setting the release behaviour for this Scheduler. */
49 private static final String KEY_SCHEDULED_RELEASE = "rx3.io-scheduled-release";
50 static boolean USE_SCHEDULED_RELEASE;
51
52 static final CachedWorkerPool NONE;
53
54 static {
55 KEEP_ALIVE_TIME = Long.getLong(KEY_KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_DEFAULT);
56
57 SHUTDOWN_THREAD_WORKER = new ThreadWorker(new RxThreadFactory("RxCachedThreadSchedulerShutdown"));
58 SHUTDOWN_THREAD_WORKER.dispose();
59
60 int priority = Math.max(Thread.MIN_PRIORITY, Math.min(Thread.MAX_PRIORITY,
61 Integer.getInteger(KEY_IO_PRIORITY, Thread.NORM_PRIORITY)));
62
63 WORKER_THREAD_FACTORY = new RxThreadFactory(WORKER_THREAD_NAME_PREFIX, priority);
64
65 EVICTOR_THREAD_FACTORY = new RxThreadFactory(EVICTOR_THREAD_NAME_PREFIX, priority);
66
67 USE_SCHEDULED_RELEASE = Boolean.getBoolean(KEY_SCHEDULED_RELEASE);
68
69 NONE = new CachedWorkerPool(0, null, WORKER_THREAD_FACTORY);
70 NONE.shutdown();
71 }
72
73 static final class CachedWorkerPool implements Runnable {
74 private final long keepAliveTime;
75 private final ConcurrentLinkedQueue<ThreadWorker> expiringWorkerQueue;
76 final CompositeDisposable allWorkers;
77 private final ScheduledExecutorService evictorService;
78 private final Future<?> evictorTask;
79 private final ThreadFactory threadFactory;
80
81 CachedWorkerPool(long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) {
82 this.keepAliveTime = unit != null ? unit.toNanos(keepAliveTime) : 0L;
83 this.expiringWorkerQueue = new ConcurrentLinkedQueue<>();
84 this.allWorkers = new CompositeDisposable();
85 this.threadFactory = threadFactory;
86
87 ScheduledExecutorService evictor = null;
88 Future<?> task = null;
89 if (unit != null) {
90 evictor = Executors.newScheduledThreadPool(1, EVICTOR_THREAD_FACTORY);
91 task = evictor.scheduleWithFixedDelay(this, this.keepAliveTime, this.keepAliveTime, TimeUnit.NANOSECONDS);
92 }
93 evictorService = evictor;
94 evictorTask = task;
95 }
96
97 @Override
98 public void run() {
99 evictExpiredWorkers(expiringWorkerQueue, allWorkers);
100 }
101
102 ThreadWorker get() {
103 if (allWorkers.isDisposed()) {
104 return SHUTDOWN_THREAD_WORKER;
105 }
106 while (!expiringWorkerQueue.isEmpty()) {
107 ThreadWorker threadWorker = expiringWorkerQueue.poll();
108 if (threadWorker != null) {
109 return threadWorker;
110 }
111 }
112
113 // No cached worker found, so create a new one.
114 ThreadWorker w = new ThreadWorker(threadFactory);
115 allWorkers.add(w);
116 return w;
117 }
118
119 void release(ThreadWorker threadWorker) {
120 // Refresh expire time before putting worker back in pool
121 threadWorker.setExpirationTime(now() + keepAliveTime);
122
123 expiringWorkerQueue.offer(threadWorker);
124 }
125
126 static void evictExpiredWorkers(ConcurrentLinkedQueue<ThreadWorker> expiringWorkerQueue, CompositeDisposable allWorkers) {
127 if (!expiringWorkerQueue.isEmpty()) {
128 long currentTimestamp = now();
129
130 for (ThreadWorker threadWorker : expiringWorkerQueue) {
131 if (threadWorker.getExpirationTime() <= currentTimestamp) {
132 if (expiringWorkerQueue.remove(threadWorker)) {
133 allWorkers.remove(threadWorker);
134 }
135 } else {
136 // Queue is ordered with the worker that will expire first in the beginning, so when we
137 // find a non-expired worker we can stop evicting.
138 break;
139 }
140 }
141 }
142 }
143
144 static long now() {
145 return System.nanoTime();
146 }
147
148 void shutdown() {
149 allWorkers.dispose();
150 if (evictorTask != null) {
151 evictorTask.cancel(true);
152 }
153 if (evictorService != null) {
154 evictorService.shutdownNow();
155 }
156 }
157 }
158
159 public IoScheduler() {
160 this(WORKER_THREAD_FACTORY);
161 }
162
163 /**
164 * Constructs an IoScheduler with the given thread factory and starts the pool of workers.
165 * @param threadFactory thread factory to use for creating worker threads. Note that this takes precedence over any
166 * system properties for configuring new thread creation. Cannot be null.
167 */
168 public IoScheduler(ThreadFactory threadFactory) {
169 this.threadFactory = threadFactory;
170 this.pool = new AtomicReference<>(NONE);
171 start();
172 }
173
174 @Override
175 public void start() {
176 CachedWorkerPool update = new CachedWorkerPool(KEEP_ALIVE_TIME, KEEP_ALIVE_UNIT, threadFactory);
177 if (!pool.compareAndSet(NONE, update)) {
178 update.shutdown();
179 }
180 }
181
182 @Override
183 public void shutdown() {
184 CachedWorkerPool curr = pool.getAndSet(NONE);
185 if (curr != NONE) {
186 curr.shutdown();
187 }
188 }
189
190 @NonNull
191 @Override
192 public Worker createWorker() {
193 return new EventLoopWorker(pool.get());
194 }
195
196 public int size() {
197 return pool.get().allWorkers.size();
198 }
199
200 static final class EventLoopWorker extends Scheduler.Worker implements Runnable {
201 private final CompositeDisposable tasks;
202 private final CachedWorkerPool pool;
203 private final ThreadWorker threadWorker;
204
205 final AtomicBoolean once = new AtomicBoolean();
206
207 EventLoopWorker(CachedWorkerPool pool) {
208 this.pool = pool;
209 this.tasks = new CompositeDisposable();
210 this.threadWorker = pool.get();
211 }
212
213 @Override
214 public void dispose() {
215 if (once.compareAndSet(false, true)) {
216 tasks.dispose();
217
218 if (USE_SCHEDULED_RELEASE) {
219 threadWorker.scheduleActual(this, 0, TimeUnit.NANOSECONDS, null);
220 } else {
221 // releasing the pool should be the last action
222 pool.release(threadWorker);
223 }
224 }
225 }
226
227 @Override
228 public void run() {
229 pool.release(threadWorker);
230 }
231
232 @Override
233 public boolean isDisposed() {
234 return once.get();
235 }
236
237 @NonNull
238 @Override
239 public Disposable schedule(@NonNull Runnable action, long delayTime, @NonNull TimeUnit unit) {
240 if (tasks.isDisposed()) {
241 // don't schedule, we are unsubscribed
242 return EmptyDisposable.INSTANCE;
243 }
244
245 return threadWorker.scheduleActual(action, delayTime, unit, tasks);
246 }
247 }
248
249 static final class ThreadWorker extends NewThreadWorker {
250
251 long expirationTime;
252
253 ThreadWorker(ThreadFactory threadFactory) {
254 super(threadFactory);
255 this.expirationTime = 0L;
256 }
257
258 public long getExpirationTime() {
259 return expirationTime;
260 }
261
262 public void setExpirationTime(long expirationTime) {
263 this.expirationTime = expirationTime;
264 }
265 }
266 }