-
Notifications
You must be signed in to change notification settings - Fork 25.5k
Introduce RefCountingRunnable #92620
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
elasticsearchmachine
merged 9 commits into
elastic:main
from
DaveCTurner:2023-01-03-RefCountingRunnable
Jan 9, 2023
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
1d15a29
Introduce RefCountingRunnable
DaveCTurner 8eb65c2
Merge branch 'main' into 2023-01-03-RefCountingRunnable
DaveCTurner e6fdb18
Fixup
DaveCTurner 7b8ffaf
Merge branch 'main' into 2023-01-03-RefCountingRunnable
DaveCTurner 7422057
Javadocs
DaveCTurner 85d81b3
Merge branch 'main' into 2023-01-03-RefCountingRunnable
DaveCTurner 01e9618
Enforce one-shot closes as per Releasable contract
DaveCTurner 94bcfc6
Fix test
DaveCTurner eabfec5
Merge remote-tracking branch 'upstream/main' into 2023-01-03-RefCount…
DaveCTurner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
144 changes: 144 additions & 0 deletions
144
server/src/main/java/org/elasticsearch/action/support/RefCountingRunnable.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
/* | ||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
* or more contributor license agreements. Licensed under the Elastic License | ||
* 2.0 and the Server Side Public License, v 1; you may not use this file except | ||
* in compliance with, at your election, the Elastic License 2.0 or the Server | ||
* Side Public License, v 1. | ||
*/ | ||
|
||
package org.elasticsearch.action.support; | ||
|
||
import org.apache.logging.log4j.LogManager; | ||
import org.apache.logging.log4j.Logger; | ||
import org.elasticsearch.action.ActionListener; | ||
import org.elasticsearch.common.util.concurrent.CountDown; | ||
import org.elasticsearch.core.AbstractRefCounted; | ||
import org.elasticsearch.core.RefCounted; | ||
import org.elasticsearch.core.Releasable; | ||
|
||
import java.util.concurrent.atomic.AtomicBoolean; | ||
|
||
/** | ||
* A mechanism to trigger an action on the completion of some (dynamic) collection of other actions. Basic usage is as follows: | ||
* | ||
* <pre> | ||
* try (var refs = new RefCountingRunnable(finalRunnable)) { | ||
* for (var item : collection) { | ||
* runAsyncAction(item, refs.acquire()); // releases the acquired ref on completion | ||
* } | ||
* } | ||
* </pre> | ||
* | ||
* The delegate action is completed when execution leaves the try-with-resources block and every acquired reference is released. Unlike a | ||
* {@link CountDown} there is no need to declare the number of subsidiary actions up front (refs can be acquired dynamically as needed) nor | ||
* does the caller need to check for completion each time a reference is released. Moreover even outside the try-with-resources block you | ||
* can continue to acquire additional listeners, even in a separate thread, as long as there's at least one listener outstanding: | ||
* | ||
* <pre> | ||
* try (var refs = new RefCountingRunnable(finalRunnable)) { | ||
* for (var item : collection) { | ||
* if (condition(item)) { | ||
* runAsyncAction(item, refs.acquire()); | ||
* } | ||
* } | ||
* if (flag) { | ||
* runOneOffAsyncAction(refs.acquire()); | ||
* return; | ||
* } | ||
* for (var item : otherCollection) { | ||
* var itemRef = refs.acquire(); // delays completion while the background action is pending | ||
* executorService.execute(() -> { | ||
* try (var ignored = itemRef) { | ||
* if (condition(item)) { | ||
* runOtherAsyncAction(item, refs.acquire()); | ||
* } | ||
* } | ||
* }); | ||
* } | ||
* } | ||
* </pre> | ||
* | ||
* In particular (and also unlike a {@link CountDown}) this works even if you don't acquire any extra refs at all: in that case, the | ||
* delegate action executes at the end of the try-with-resources block. | ||
*/ | ||
public final class RefCountingRunnable implements Releasable { | ||
thecoop marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
private static final Logger logger = LogManager.getLogger(RefCountingRunnable.class); | ||
static final String ALREADY_CLOSED_MESSAGE = "already closed, cannot acquire or release any further refs"; | ||
|
||
private final RefCounted refCounted; | ||
private final AtomicBoolean originalRefReleased = new AtomicBoolean(); | ||
|
||
private class AcquiredRef implements Releasable { | ||
private final AtomicBoolean released = new AtomicBoolean(); | ||
|
||
@Override | ||
public void close() { | ||
releaseRef(released); | ||
} | ||
|
||
@Override | ||
public String toString() { | ||
return RefCountingRunnable.this.toString(); | ||
} | ||
} | ||
|
||
/** | ||
* Construct a {@link RefCountingRunnable} which executes {@code delegate} when all refs are released. | ||
* @param delegate The action to execute when all refs are released. This action must not throw any exception. | ||
*/ | ||
public RefCountingRunnable(Runnable delegate) { | ||
this.refCounted = AbstractRefCounted.of(delegate); | ||
} | ||
|
||
/** | ||
* Acquire a reference to this object and return an action which releases it. The delegate {@link Runnable} is called when all its | ||
* references have been released. | ||
* | ||
* Callers must take care to close the returned resource exactly once. This deviates from the contract of {@link java.io.Closeable}. | ||
*/ | ||
public Releasable acquire() { | ||
if (refCounted.tryIncRef()) { | ||
return new AcquiredRef(); | ||
} | ||
assert false : ALREADY_CLOSED_MESSAGE; | ||
throw new IllegalStateException(ALREADY_CLOSED_MESSAGE); | ||
} | ||
|
||
/** | ||
* Acquire a reference to this object and return a listener which releases it when notified. The delegate {@link Runnable} is called | ||
* when all its references have been released. | ||
*/ | ||
public ActionListener<Void> acquireListener() { | ||
return ActionListener.releasing(acquire()); | ||
} | ||
|
||
/** | ||
* Release the original reference to this object, which executes the delegate {@link Runnable} if there are no other references. | ||
* | ||
* Callers must take care to close this resource exactly once. This deviates from the contract of {@link java.io.Closeable}. | ||
*/ | ||
@Override | ||
public void close() { | ||
releaseRef(originalRefReleased); | ||
} | ||
|
||
private void releaseRef(AtomicBoolean released) { | ||
if (released.compareAndSet(false, true)) { | ||
try { | ||
refCounted.decRef(); | ||
} catch (Exception e) { | ||
logger.error("exception in delegate", e); | ||
assert false : e; | ||
} | ||
} else { | ||
assert false : "already closed"; | ||
} | ||
} | ||
|
||
@Override | ||
public String toString() { | ||
return refCounted.toString(); | ||
} | ||
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.