Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -275,29 +275,7 @@ static <Response> ActionListener<Response> runBefore(ActionListener<Response> de
* and {@link #onFailure(Exception)} of the provided listener will be called at most once.
*/
static <Response> ActionListener<Response> notifyOnce(ActionListener<Response> delegate) {
final var delegateRef = new AtomicReference<>(delegate);
return new ActionListener<>() {
@Override
public void onResponse(Response response) {
final var acquired = delegateRef.getAndSet(null);
if (acquired != null) {
acquired.onResponse(response);
}
}

@Override
public void onFailure(Exception e) {
final var acquired = delegateRef.getAndSet(null);
if (acquired != null) {
safeOnFailure(acquired, e);
}
}

@Override
public String toString() {
return "notifyOnce[" + delegateRef.get() + "]";
}
};
return new ActionListenerImplementations.NotifyOnceActionListener<>(delegate);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import org.elasticsearch.core.Releasable;
import org.elasticsearch.core.Releasables;

import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

Expand Down Expand Up @@ -250,4 +251,35 @@ public String toString() {
return super.toString() + "/" + runBefore;
}
}

// Extend AtomicReference directly for minimum memory overhead and indirection.
static final class NotifyOnceActionListener<Response> extends AtomicReference<ActionListener<Response>>
implements
ActionListener<Response> {

NotifyOnceActionListener(ActionListener<Response> delegate) {
super(delegate);
}

@Override
public void onResponse(Response response) {
final var acquired = getAndSet(null);
if (acquired != null) {
acquired.onResponse(response);
}
}

@Override
public void onFailure(Exception e) {
final var acquired = getAndSet(null);
if (acquired != null) {
safeOnFailure(acquired, e);
}
}

@Override
public String toString() {
return "notifyOnce[" + get() + "]";
}
}
}