Skip to content

Commit faf9d65

Browse files
committed
Fix a potential memory leak in schedulePeriodically
1 parent 68f7f66 commit faf9d65

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

src/main/java/rx/Scheduler.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import rx.functions.Action0;
2121
import rx.schedulers.Schedulers;
2222
import rx.subscriptions.MultipleAssignmentSubscription;
23+
import rx.subscriptions.SerialSubscription;
2324

2425
/**
2526
* A {@code Scheduler} is an object that schedules units of work. You can find common implementations of this
@@ -119,11 +120,17 @@ public void call() {
119120
if (!mas.isUnsubscribed()) {
120121
action.call();
121122
long nextTick = startInNanos + (++count * periodInNanos);
122-
mas.set(schedule(this, nextTick - TimeUnit.MILLISECONDS.toNanos(now()), TimeUnit.NANOSECONDS));
123+
SerialSubscription s = new SerialSubscription();
124+
// Should call `mas.set` before `schedule`, or the new Subscription may replace the old one.
125+
mas.set(s);
126+
s.set(schedule(this, nextTick - TimeUnit.MILLISECONDS.toNanos(now()), TimeUnit.NANOSECONDS));
123127
}
124128
}
125129
};
126-
mas.set(schedule(recursiveAction, initialDelay, unit));
130+
SerialSubscription s = new SerialSubscription();
131+
// Should call `mas.set` before `schedule`, or the new Subscription may replace the old one.
132+
mas.set(s);
133+
s.set(schedule(recursiveAction, initialDelay, unit));
127134
return mas;
128135
}
129136

0 commit comments

Comments
 (0)