Skip to content

1.x: improve ExecutorScheduler worker unsubscription #3842

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 8, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/main/java/rx/schedulers/ExecutorScheduler.java
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,20 @@ public Subscription schedule(Action0 action) {
@Override
public void run() {
do {
if (tasks.isUnsubscribed()) {
queue.clear();
return;
}

ScheduledAction sa = queue.poll();
if (sa == null) {
return;
}

if (!sa.isUnsubscribed()) {
sa.run();
}
} while (wip.decrementAndGet() > 0);
} while (wip.decrementAndGet() != 0);
}

@Override
Expand Down Expand Up @@ -170,6 +179,7 @@ public boolean isUnsubscribed() {
@Override
public void unsubscribe() {
tasks.unsubscribe();
queue.clear();
}

}
Expand Down
30 changes: 30 additions & 0 deletions src/test/java/rx/schedulers/ExecutorSchedulerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
import static org.junit.Assert.*;

import java.lang.management.*;
import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Assert;
import org.junit.Test;

import rx.*;
Expand Down Expand Up @@ -275,4 +277,32 @@ public void call() {

assertFalse(w.tasks.hasSubscriptions());
}

@Test
public void workerUnderConcurrentUnsubscribeShouldNotAllowLaterTasksToRunDueToUnsubscriptionRace() {
Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(1));
for (int i = 0; i< 1000; i++) {
Worker worker = scheduler.createWorker();
final Queue<Integer> q = new ConcurrentLinkedQueue<Integer>();
Action0 action1 = new Action0() {

@Override
public void call() {
q.add(1);
}};
Action0 action2 = new Action0() {

@Override
public void call() {
q.add(2);
}};
worker.schedule(action1);
worker.schedule(action2);
worker.unsubscribe();
if (q.size()==1 && q.poll() == 2) {
//expect a queue of 1,2 or 1. If queue is just 2 then we have a problem!
Assert.fail("wrong order on loop " + i);
}
}
}
}