-
Notifications
You must be signed in to change notification settings - Fork 534
/
Copy pathNumberSubscriberThatHopsThreads.java
64 lines (54 loc) · 1.86 KB
/
NumberSubscriberThatHopsThreads.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package org.reactivestreams.example.unicast;
import java.util.concurrent.ArrayBlockingQueue;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
class NumberSubscriberThatHopsThreads implements Subscriber<Integer> {
final int BUFFER_SIZE = 10;
private final ArrayBlockingQueue<Integer> buffer = new ArrayBlockingQueue<>(BUFFER_SIZE);
private volatile boolean terminated = false;
private final String token;
NumberSubscriberThatHopsThreads(String token) {
this.token = token;
}
@Override
public void onSubscribe(Subscription s) {
System.out.println("onSubscribe => request " + BUFFER_SIZE);
s.signalAdditionalDemand(BUFFER_SIZE);
startAsyncWork(s);
}
@Override
public void onNext(Integer t) {
buffer.add(t);
}
@Override
public void onError(Throwable t) {
terminated = true;
throw new RuntimeException(t);
}
@Override
public void onCompleted() {
terminated = true;
}
private void startAsyncWork(final Subscription s) {
System.out.println("**** Start new worker thread");
/* don't write real code like this! just for quick demo */
new Thread(new Runnable() {
public void run() {
while (!terminated) {
Integer v = buffer.poll();
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
if (buffer.size() < 3) {
s.signalAdditionalDemand(BUFFER_SIZE - buffer.size());
}
if (v != null) {
System.out.println(token + " => Did stuff with v: " + v);
}
}
}
}).start();
}
}