-
Notifications
You must be signed in to change notification settings - Fork 0
/
TemperatureValueSource.java
42 lines (33 loc) · 1.38 KB
/
TemperatureValueSource.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
package externalLegacyCodeNotUnderOurControl;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
public class TemperatureValueSource {
private final List<TemperatureListener> listenerList = Lists.newCopyOnWriteArrayList();
public TemperatureValueSource() {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(
1,
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(TemperatureValueSource.class.getSimpleName() + "-%d")
.build()
);
executorService.scheduleAtFixedRate(() -> {
int nextTemperature = ThreadLocalRandom.current().nextInt(20, 25);
listenerList.forEach(listener -> listener.onNext(nextTemperature));
}, 2, 2, TimeUnit.SECONDS);
}
public void addListener(TemperatureListener listener) {
listenerList.add(listener);
}
public boolean removeListener(TemperatureListener listener) {
return listenerList.remove(listener);
}
public interface TemperatureListener {
void onNext(int temperature);
}
}