File tree 2 files changed +41
-1
lines changed 2 files changed +41
-1
lines changed Original file line number Diff line number Diff line change @@ -96,11 +96,20 @@ public Subscription schedule(Action0 action) {
96
96
@ Override
97
97
public void run () {
98
98
do {
99
+ if (tasks .isUnsubscribed ()) {
100
+ queue .clear ();
101
+ return ;
102
+ }
103
+
99
104
ScheduledAction sa = queue .poll ();
105
+ if (sa == null ) {
106
+ return ;
107
+ }
108
+
100
109
if (!sa .isUnsubscribed ()) {
101
110
sa .run ();
102
111
}
103
- } while (wip .decrementAndGet () > 0 );
112
+ } while (wip .decrementAndGet () != 0 );
104
113
}
105
114
106
115
@ Override
@@ -170,6 +179,7 @@ public boolean isUnsubscribed() {
170
179
@ Override
171
180
public void unsubscribe () {
172
181
tasks .unsubscribe ();
182
+ queue .clear ();
173
183
}
174
184
175
185
}
Original file line number Diff line number Diff line change 18
18
import static org .junit .Assert .*;
19
19
20
20
import java .lang .management .*;
21
+ import java .util .Queue ;
21
22
import java .util .concurrent .*;
22
23
import java .util .concurrent .atomic .AtomicInteger ;
23
24
25
+ import org .junit .Assert ;
24
26
import org .junit .Test ;
25
27
26
28
import rx .*;
@@ -275,4 +277,32 @@ public void call() {
275
277
276
278
assertFalse (w .tasks .hasSubscriptions ());
277
279
}
280
+
281
+ @ Test
282
+ public void workerUnderConcurrentUnsubscribeShouldNotAllowLaterTasksToRunDueToUnsubscriptionRace () {
283
+ Scheduler scheduler = Schedulers .from (Executors .newFixedThreadPool (1 ));
284
+ for (int i = 0 ; i < 1000 ; i ++) {
285
+ Worker worker = scheduler .createWorker ();
286
+ final Queue <Integer > q = new ConcurrentLinkedQueue <Integer >();
287
+ Action0 action1 = new Action0 () {
288
+
289
+ @ Override
290
+ public void call () {
291
+ q .add (1 );
292
+ }};
293
+ Action0 action2 = new Action0 () {
294
+
295
+ @ Override
296
+ public void call () {
297
+ q .add (2 );
298
+ }};
299
+ worker .schedule (action1 );
300
+ worker .schedule (action2 );
301
+ worker .unsubscribe ();
302
+ if (q .size ()==1 && q .poll () == 2 ) {
303
+ //expect a queue of 1,2 or 1. If queue is just 2 then we have a problem!
304
+ Assert .fail ("wrong order on loop " + i );
305
+ }
306
+ }
307
+ }
278
308
}
You can’t perform that action at this time.
0 commit comments