Skip to content

Commit fe2157c

Browse files
committed
Use AtomicReference
1 parent 4e84773 commit fe2157c

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

src/main/java/rx/schedulers/Schedulers.java

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import rx.plugins.RxJavaSchedulersHook;
2626

2727
import java.util.concurrent.Executor;
28+
import java.util.concurrent.atomic.AtomicReference;
2829

2930
/**
3031
* Static factory methods for creating Schedulers.
@@ -35,13 +36,21 @@ public final class Schedulers {
3536
private final Scheduler ioScheduler;
3637
private final Scheduler newThreadScheduler;
3738

38-
private static Schedulers INSTANCE;
39+
private static final AtomicReference<Schedulers> INSTANCE = new AtomicReference<Schedulers>();
3940

40-
private static synchronized Schedulers getInstance() {
41-
if (INSTANCE == null) {
42-
INSTANCE = new Schedulers();
41+
private static Schedulers getInstance() {
42+
for (;;) {
43+
Schedulers current = INSTANCE.get();
44+
if (current != null) {
45+
return current;
46+
}
47+
current = new Schedulers();
48+
if (INSTANCE.compareAndSet(null, current)) {
49+
return current;
50+
} else {
51+
shutdown();
52+
}
4353
}
44-
return INSTANCE;
4554
}
4655

4756
private Schedulers() {
@@ -163,7 +172,7 @@ public static Scheduler from(Executor executor) {
163172
@Experimental
164173
public static void reset() {
165174
shutdown();
166-
INSTANCE = null;
175+
INSTANCE.set(null);
167176
}
168177

169178
/**
@@ -205,11 +214,11 @@ public static void shutdown() {
205214
if (s.newThreadScheduler instanceof SchedulerLifecycle) {
206215
((SchedulerLifecycle) s.newThreadScheduler).shutdown();
207216
}
208-
217+
209218
GenericScheduledExecutorService.INSTANCE.shutdown();
210-
219+
211220
RxRingBuffer.SPSC_POOL.shutdown();
212-
221+
213222
RxRingBuffer.SPMC_POOL.shutdown();
214223
}
215224
}

0 commit comments

Comments
 (0)