Avoid allocating excessive amounts of AtomicReference instances
@@ -3,7 +3,7 @@ package io.smallrye.mutiny.operators.uni;
import static io.smallrye.mutiny.helpers.EmptyUniSubscription.CANCELLED;
import static io.smallrye.mutiny.helpers.EmptyUniSubscription.DONE;
-import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import io.smallrye.mutiny.helpers.ParameterValidation;
import io.smallrye.mutiny.infrastructure.Infrastructure;
@@ -13,7 +13,10 @@ import io.smallrye.mutiny.subscription.UniSubscription;
public abstract class UniOperatorProcessor<I, O> implements UniSubscriber<I>, UniSubscription {
protected final UniSubscriber<? super O> downstream;
- protected final AtomicReference<UniSubscription> upstream = new AtomicReference<>();
+
+ private static final AtomicReferenceFieldUpdater<UniOperatorProcessor,UniSubscription> updater = AtomicReferenceFieldUpdater.newUpdater(UniOperatorProcessor.class, UniSubscription.class, "upstream");
+
+ protected volatile UniSubscription upstream;
public UniOperatorProcessor(UniSubscriber<? super O> downstream) {
this.downstream = ParameterValidation.nonNull(downstream, "downstream");
@@ -21,7 +24,7 @@ public abstract class UniOperatorProcessor<I, O> implements UniSubscriber<I>, Un
@Override
public void onSubscribe(UniSubscription subscription) {
- if (upstream.compareAndSet(null, subscription)) {
+ if (updater.compareAndSet(this, null, subscription)) {
downstream.onSubscribe(this);
} else {
subscription.cancel();
@@ -31,7 +34,7 @@ public abstract class UniOperatorProcessor<I, O> implements UniSubscriber<I>, Un
@Override
@SuppressWarnings("unchecked")
public void onItem(I item) {
- UniSubscription subscription = upstream.getAndSet(CANCELLED);
+ UniSubscription subscription = updater.getAndSet(this, CANCELLED);
if (subscription != CANCELLED) {
downstream.onItem((O) item);
}
@@ -39,7 +42,7 @@ public abstract class UniOperatorProcessor<I, O> implements UniSubscriber<I>, Un
@Override
public void onFailure(Throwable failure) {
- UniSubscription subscription = upstream.getAndSet(CANCELLED);
+ UniSubscription subscription = updater.getAndSet(this, CANCELLED);
if (subscription != CANCELLED) {
downstream.onFailure(failure);
} else {
@@ -49,13 +52,13 @@ public abstract class UniOperatorProcessor<I, O> implements UniSubscriber<I>, Un
@Override
public void cancel() {
- UniSubscription subscription = upstream.getAndSet(CANCELLED);
+ UniSubscription subscription = updater.getAndSet(this, CANCELLED);
if (subscription != null && subscription != CANCELLED && subscription != DONE) {
subscription.cancel();
}
}
public boolean isCancelled() {
- return upstream.get() == CANCELLED;
+ return upstream == CANCELLED;
}
}
