2
RxJava 내부에 대해 David Karnok이 작성한 this 문서를 읽는 동안 RxJava의 SerializedObserver
클래스에 가까운 구현 예를 직면했습니다. 그래서 질문은 왜 내부 q
변수 첫 synchronized
블록에 도입 된 것입니다RxJava SerializedObserver 구현
class ValueListEmitterLoop<T> {
List<T> queue;
boolean emitting;
Consumer<? super T> consumer;
public void emit(T value) {
synchronized (this) {
if (emitting) {
List<T> q = queue;
if (q == null) {
q = new ArrayList<>();
queue = q;
}
q.add(value);
return;
}
emitting = true;
}
consumer.accept(value);
for (;;) {
List<T> q;
synchronized (this) {
q = queue;
if (q == null) {
emitting = false;
return;
}
queue = null;
}
q.forEach(consumer);
}
}
}
: 여기에 코드? 나는 두 번째 synchronized
블록에 그 이유를 분명히 알 수 있습니다.
if (queue == null) {
queue = new ArrayList<>();
}
queue.add(value);
고맙습니다! 나는 너의 대답을 기대했다. –