Skip to content

Commit

Permalink
Release delegate ref in RunOnce (#92507)
Browse files Browse the repository at this point in the history
Like #92452 but for `RunOnce`.
  • Loading branch information
DaveCTurner authored Dec 23, 2022
1 parent 1876400 commit 0fdc754
Showing 1 changed file with 8 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,31 @@
package org.elasticsearch.common.util.concurrent;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
* Runnable that can only be run one time.
* Runnable that prevents running its delegate more than once.
*/
public class RunOnce implements Runnable {

private final Runnable delegate;
private final AtomicBoolean hasRun;
private final AtomicReference<Runnable> delegateRef;

public RunOnce(final Runnable delegate) {
this.delegate = Objects.requireNonNull(delegate);
this.hasRun = new AtomicBoolean(false);
delegateRef = new AtomicReference<>(Objects.requireNonNull(delegate));
}

@Override
public void run() {
if (hasRun.compareAndSet(false, true)) {
delegate.run();
var acquired = delegateRef.getAndSet(null);
if (acquired != null) {
acquired.run();
}
}

/**
* {@code true} if the {@link RunOnce} has been executed once.
*/
public boolean hasRun() {
return hasRun.get();
return delegateRef.get() == null;
}
}

0 comments on commit 0fdc754

Please sign in to comment.