-
Notifications
You must be signed in to change notification settings - Fork 25.3k
Refactor ForEachProcessor to use iteration instead of recursion #51104
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
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
6ecd379
Refactor ForEachProcessor to use iteration instead of recursion
probakowski 0d9276d
Unused imports removed
probakowski 089fca0
Removed unnecessary synchronization, tests refactorings
probakowski 03b0ab6
Unused import removed
probakowski bf8fdc2
Unused import removed
probakowski 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -30,9 +30,8 @@ | |
import java.util.List; | ||
import java.util.Map; | ||
import java.util.Set; | ||
import java.util.concurrent.CopyOnWriteArrayList; | ||
import java.util.concurrent.atomic.AtomicBoolean; | ||
import java.util.function.BiConsumer; | ||
import java.util.function.Consumer; | ||
|
||
import static org.elasticsearch.ingest.ConfigurationUtils.newConfigurationException; | ||
import static org.elasticsearch.ingest.ConfigurationUtils.readBooleanProperty; | ||
|
@@ -50,19 +49,16 @@ | |
public final class ForEachProcessor extends AbstractProcessor implements WrappingProcessor { | ||
|
||
public static final String TYPE = "foreach"; | ||
static final int MAX_RECURSE_PER_THREAD = 10; | ||
|
||
private final String field; | ||
private final Processor processor; | ||
private final boolean ignoreMissing; | ||
private final Consumer<Runnable> genericExecutor; | ||
|
||
ForEachProcessor(String tag, String field, Processor processor, boolean ignoreMissing, Consumer<Runnable> genericExecutor) { | ||
ForEachProcessor(String tag, String field, Processor processor, boolean ignoreMissing) { | ||
super(tag); | ||
this.field = field; | ||
this.processor = processor; | ||
this.ignoreMissing = ignoreMissing; | ||
this.genericExecutor = genericExecutor; | ||
} | ||
|
||
boolean isIgnoreMissing() { | ||
|
@@ -79,41 +75,35 @@ public void execute(IngestDocument ingestDocument, BiConsumer<IngestDocument, Ex | |
handler.accept(null, new IllegalArgumentException("field [" + field + "] is null, cannot loop over its elements.")); | ||
} | ||
} else { | ||
List<Object> newValues = new CopyOnWriteArrayList<>(); | ||
innerExecute(0, values, newValues, ingestDocument, handler); | ||
innerExecute(0, values, new ArrayList<>(values.size()), ingestDocument, handler); | ||
} | ||
} | ||
|
||
void innerExecute(int index, List<?> values, List<Object> newValues, IngestDocument document, | ||
BiConsumer<IngestDocument, Exception> handler) { | ||
for (; index < values.size(); index++) { | ||
AtomicBoolean shouldContinueHere = new AtomicBoolean(); | ||
Object value = values.get(index); | ||
Object previousValue = document.getIngestMetadata().put("_value", value); | ||
int nextIndex = index + 1; | ||
processor.execute(document, (result, e) -> { | ||
newValues.add(document.getIngestMetadata().put("_value", previousValue)); | ||
if (e != null || result == null) { | ||
handler.accept(result, e); | ||
} else if (shouldContinueHere.getAndSet(true)) { | ||
innerExecute(nextIndex, values, newValues, document, handler); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In this case recursion does happen, but we're not risking a SO here, because it always a different thread would get here. |
||
} | ||
}); | ||
|
||
if (shouldContinueHere.getAndSet(true) == false) { | ||
return; | ||
} | ||
} | ||
|
||
if (index == values.size()) { | ||
document.setFieldValue(field, new ArrayList<>(newValues)); | ||
handler.accept(document, null); | ||
return; | ||
} | ||
|
||
Object value = values.get(index); | ||
Object previousValue = document.getIngestMetadata().put("_value", value); | ||
final Thread thread = Thread.currentThread(); | ||
processor.execute(document, (result, e) -> { | ||
if (e != null) { | ||
newValues.add(document.getIngestMetadata().put("_value", previousValue)); | ||
handler.accept(null, e); | ||
} else if (result == null) { | ||
handler.accept(null, null); | ||
} else { | ||
newValues.add(document.getIngestMetadata().put("_value", previousValue)); | ||
if (thread == Thread.currentThread() && (index + 1) % MAX_RECURSE_PER_THREAD == 0) { | ||
// we are on the same thread and we need to fork to another thread to avoid recursive stack overflow on a single thread | ||
// only fork after 10 recursive calls, then fork every 10 to keep the number of threads down | ||
genericExecutor.accept(() -> innerExecute(index + 1, values, newValues, document, handler)); | ||
} else { | ||
// we are on a different thread (we went asynchronous), it's safe to recurse | ||
// or we have recursed less then 10 times with the same thread, it's safe to recurse | ||
innerExecute(index + 1, values, newValues, document, handler); | ||
} | ||
} | ||
}); | ||
} | ||
|
||
@Override | ||
|
@@ -137,11 +127,9 @@ public Processor getInnerProcessor() { | |
public static final class Factory implements Processor.Factory { | ||
|
||
private final ScriptService scriptService; | ||
private final Consumer<Runnable> genericExecutor; | ||
|
||
Factory(ScriptService scriptService, Consumer<Runnable> genericExecutor) { | ||
Factory(ScriptService scriptService) { | ||
this.scriptService = scriptService; | ||
this.genericExecutor = genericExecutor; | ||
} | ||
|
||
@Override | ||
|
@@ -157,7 +145,7 @@ public ForEachProcessor create(Map<String, Processor.Factory> factories, String | |
Map.Entry<String, Map<String, Object>> entry = entries.iterator().next(); | ||
Processor processor = | ||
ConfigurationUtils.readProcessor(factories, scriptService, entry.getKey(), entry.getValue()); | ||
return new ForEachProcessor(tag, field, processor, ignoreMissing, genericExecutor); | ||
return new ForEachProcessor(tag, field, processor, ignoreMissing); | ||
} | ||
} | ||
} |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I like this approach. In the case of inner processor going async; whichever thread sets this atomic boolean last should continue with the next value.
And in the case inner processor doesn't go async then on the second
getAndSet(...)
the current thread continues with the next value.I do wonder if this variable can be renamed to describe this beter.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wonder about this scenario:
shouldContinueHere
first.shouldContinueHere
first.newValues
simultaneously.Is this scenario possible? And if so should have protection against this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If current thread hits
shouldContinueHere
first, then it seesfalse
and ends the loop (returns).If it hits it second that means it's after async call already finished and other thread updated
newValues
already.As you mentioned in first comment only thread that checks
shouldContinueHere
last actually proceedsDoes it answer your question or did I misunderstand the scenario?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for clarifying. I misinterpreted the if statement on line 98 when looking at it this morning.
It is not possible that multiple values from the list are handled concurrently.