Apache Lucene open-source search software
Simplify TaskExecutor API (#12603)
Luca Cavannae93cdd127027
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex f3255f5c6d8..9f036b0b17d 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -150,6 +150,9 @@ Improvements* GITHUB#12574: Make TaskExecutor public so that it can be retrieved from the searcher and usedoutside of the o.a.l.search package (Luca Cavanna)+* GITHUB#12603: Simplify the TaskExecutor API by exposing a single invokeAll method that takes a+ collection of callables, executes them and returns their results (Luca Cavanna)+Optimizations---------------------* GITHUB#12183: Make TermStates#build concurrent. (Shubham Chaudhary)diff --git a/lucene/core/src/java/org/apache/lucene/index/TermStates.java b/lucene/core/src/java/org/apache/lucene/index/TermStates.javaindex a8472bac0d0..7efa8f8ee0c 100644--- a/lucene/core/src/java/org/apache/lucene/index/TermStates.java+++ b/lucene/core/src/java/org/apache/lucene/index/TermStates.java@@ -17,8 +17,10 @@package org.apache.lucene.index;import java.io.IOException;+import java.util.ArrayList;import java.util.Arrays;import java.util.List;+import java.util.concurrent.Callable;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.TaskExecutor;@@ -98,23 +100,20 @@ public final class TermStates {TaskExecutor taskExecutor = indexSearcher.getTaskExecutor();if (taskExecutor != null) {// build the term states concurrently- List<TaskExecutor.Task<TermStateInfo>> tasks =- context.leaves().stream()- .map(- ctx ->- taskExecutor.createTask(- () -> {- TermsEnum termsEnum = loadTermsEnum(ctx, term);- if (termsEnum != null) {- return new TermStateInfo(- termsEnum.termState(),- ctx.ord,- termsEnum.docFreq(),- termsEnum.totalTermFreq());- }- return null;- }))- .toList();+ List<Callable<TermStateInfo>> tasks = new ArrayList<>(context.leaves().size());+ for (LeafReaderContext ctx : context.leaves()) {+ tasks.add(+ () -> {+ TermsEnum termsEnum = loadTermsEnum(ctx, term);+ return termsEnum == null+ ? null+ : new TermStateInfo(+ termsEnum.termState(),+ ctx.ord,+ termsEnum.docFreq(),+ termsEnum.totalTermFreq());+ });+ }List<TermStateInfo> resultInfos = taskExecutor.invokeAll(tasks);for (TermStateInfo info : resultInfos) {if (info != null) {diff --git a/lucene/core/src/java/org/apache/lucene/search/AbstractKnnVectorQuery.java b/lucene/core/src/java/org/apache/lucene/search/AbstractKnnVectorQuery.javaindex e28536ba04c..34b8e318ed1 100644--- a/lucene/core/src/java/org/apache/lucene/search/AbstractKnnVectorQuery.java+++ b/lucene/core/src/java/org/apache/lucene/search/AbstractKnnVectorQuery.java@@ -24,6 +24,7 @@ import java.util.Arrays;import java.util.Comparator;import java.util.List;import java.util.Objects;+import java.util.concurrent.Callable;import org.apache.lucene.codecs.KnnVectorsReader;import org.apache.lucene.index.FieldInfo;import org.apache.lucene.index.IndexReader;@@ -104,9 +105,9 @@ abstract class AbstractKnnVectorQuery extends Query {private TopDocs[] parallelSearch(List<LeafReaderContext> leafReaderContexts, Weight filterWeight, TaskExecutor taskExecutor)throws IOException {- List<TaskExecutor.Task<TopDocs>> tasks = new ArrayList<>();+ List<Callable<TopDocs>> tasks = new ArrayList<>(leafReaderContexts.size());for (LeafReaderContext context : leafReaderContexts) {- tasks.add(taskExecutor.createTask(() -> searchLeaf(context, filterWeight)));+ tasks.add(() -> searchLeaf(context, filterWeight));}return taskExecutor.invokeAll(tasks).toArray(TopDocs[]::new);}diff --git a/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java b/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.javaindex e3b68879c70..5ccedd53531 100644--- a/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java+++ b/lucene/core/src/java/org/apache/lucene/search/IndexSearcher.java@@ -24,6 +24,7 @@ import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.Objects;+import java.util.concurrent.Callable;import java.util.concurrent.Executor;import java.util.function.Function;import java.util.function.Supplier;@@ -667,17 +668,15 @@ public class IndexSearcher {"CollectorManager does not always produce collectors with the same score mode");}}- final List<TaskExecutor.Task<C>> listTasks = new ArrayList<>();+ final List<Callable<C>> listTasks = new ArrayList<>(leafSlices.length);for (int i = 0; i < leafSlices.length; ++i) {final LeafReaderContext[] leaves = leafSlices[i].leaves;final C collector = collectors.get(i);- TaskExecutor.Task<C> task =- taskExecutor.createTask(- () -> {- search(Arrays.asList(leaves), weight, collector);- return collector;- });- listTasks.add(task);+ listTasks.add(+ () -> {+ search(Arrays.asList(leaves), weight, collector);+ return collector;+ });}List<C> results = taskExecutor.invokeAll(listTasks);return collectorManager.reduce(results);diff --git a/lucene/core/src/java/org/apache/lucene/search/TaskExecutor.java b/lucene/core/src/java/org/apache/lucene/search/TaskExecutor.javaindex 6e64df31400..b1dbc27a280 100644--- a/lucene/core/src/java/org/apache/lucene/search/TaskExecutor.java+++ b/lucene/core/src/java/org/apache/lucene/search/TaskExecutor.java@@ -32,14 +32,13 @@ import org.apache.lucene.util.ThreadInterruptedException;/*** Executor wrapper responsible for the execution of concurrent tasks. Used to parallelize search- * across segments as well as query rewrite in some cases. Exposes a {@link #createTask(Callable)}- * method to create tasks given a {@link Callable}, as well as the {@link #invokeAll(Collection)}- * method to execute a set of tasks concurrently. Once all tasks are submitted to the executor, it- * blocks and wait for all tasks to be completed, and then returns a list with the obtained results.- * Ensures that the underlying executor is only used for top-level {@link #invokeAll(Collection)}- * calls, and not for potential {@link #invokeAll(Collection)} calls made from one of the tasks.- * This is to prevent deadlock with certain types of pool based executors (e.g. {@link- * java.util.concurrent.ThreadPoolExecutor}).+ * across segments as well as query rewrite in some cases. Exposes a single {@link+ * #invokeAll(Collection)} method that takes a collection of {@link Callable}s and executes them+ * concurrently/ Once all tasks are submitted to the executor, it blocks and wait for all tasks to+ * be completed, and then returns a list with the obtained results. Ensures that the underlying+ * executor is only used for top-level {@link #invokeAll(Collection)} calls, and not for potential+ * {@link #invokeAll(Collection)} calls made from one of the tasks. This is to prevent deadlock with+ * certain types of pool based executors (e.g. {@link java.util.concurrent.ThreadPoolExecutor}).** @lucene.experimental*/@@ -56,24 +55,25 @@ public final class TaskExecutor {}/**- * Execute all the tasks provided as an argument, wait for them to complete and return the+ * Execute all the callables provided as an argument, wait for them to complete and return the* obtained results.*- * @param tasks the tasks to execute+ * @param callables the callables to execute* @return a list containing the results from the tasks execution* @param <T> the return type of the task execution*/- public <T> List<T> invokeAll(Collection<Task<T>> tasks) throws IOException {- if (numberOfRunningTasksInCurrentThread.get() > 0) {- for (Task<T> task : tasks) {+ public <T> List<T> invokeAll(Collection<Callable<T>> callables) throws IOException {+ List<Task<T>> tasks = new ArrayList<>(callables.size());+ boolean runOnCallerThread = numberOfRunningTasksInCurrentThread.get() > 0;+ for (Callable<T> callable : callables) {+ Task<T> task = new Task<>(callable);+ tasks.add(task);+ if (runOnCallerThread) {task.run();- }- } else {- for (Runnable task : tasks) {+ } else {executor.execute(task);}}-final List<T> results = new ArrayList<>();for (Future<T> future : tasks) {try {@@ -87,24 +87,13 @@ public final class TaskExecutor {return results;}- /**- * Creates a task given the provided {@link Callable}- *- * @param callable the callable to be executed as part of the task- * @return the created task- * @param <C> the return type of the task- */- public <C> Task<C> createTask(Callable<C> callable) {- return new Task<>(callable);- }-/*** Extension of {@link FutureTask} that tracks the number of tasks that are running in each* thread.** @param <V> the return type of the task*/- public static final class Task<V> extends FutureTask<V> {+ private static final class Task<V> extends FutureTask<V> {private Task(Callable<V> callable) {super(callable);}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestTaskExecutor.java b/lucene/core/src/test/org/apache/lucene/search/TestTaskExecutor.javaindex 51183214728..89ccc03a3fe 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestTaskExecutor.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestTaskExecutor.java@@ -50,55 +50,59 @@ public class TestTaskExecutor extends LuceneTestCase {public void testUnwrapIOExceptionFromExecutionException() {TaskExecutor taskExecutor = new TaskExecutor(executorService);- TaskExecutor.Task<?> task =- taskExecutor.createTask(- () -> {- throw new IOException("io exception");- });IOException ioException =expectThrows(- IOException.class, () -> taskExecutor.invokeAll(Collections.singletonList(task)));+ IOException.class,+ () ->+ taskExecutor.invokeAll(+ Collections.singletonList(+ () -> {+ throw new IOException("io exception");+ })));assertEquals("io exception", ioException.getMessage());}public void testUnwrapRuntimeExceptionFromExecutionException() {TaskExecutor taskExecutor = new TaskExecutor(executorService);- TaskExecutor.Task<?> task =- taskExecutor.createTask(- () -> {- throw new RuntimeException("runtime");- });RuntimeException runtimeException =expectThrows(- RuntimeException.class, () -> taskExecutor.invokeAll(Collections.singletonList(task)));+ RuntimeException.class,+ () ->+ taskExecutor.invokeAll(+ Collections.singletonList(+ () -> {+ throw new RuntimeException("runtime");+ })));assertEquals("runtime", runtimeException.getMessage());assertNull(runtimeException.getCause());}public void testUnwrapErrorFromExecutionException() {TaskExecutor taskExecutor = new TaskExecutor(executorService);- TaskExecutor.Task<?> task =- taskExecutor.createTask(- () -> {- throw new OutOfMemoryError("oom");- });OutOfMemoryError outOfMemoryError =expectThrows(- OutOfMemoryError.class, () -> taskExecutor.invokeAll(Collections.singletonList(task)));+ OutOfMemoryError.class,+ () ->+ taskExecutor.invokeAll(+ Collections.singletonList(+ () -> {+ throw new OutOfMemoryError("oom");+ })));assertEquals("oom", outOfMemoryError.getMessage());assertNull(outOfMemoryError.getCause());}public void testUnwrappedExceptions() {TaskExecutor taskExecutor = new TaskExecutor(executorService);- TaskExecutor.Task<?> task =- taskExecutor.createTask(- () -> {- throw new Exception("exc");- });RuntimeException runtimeException =expectThrows(- RuntimeException.class, () -> taskExecutor.invokeAll(Collections.singletonList(task)));+ RuntimeException.class,+ () ->+ taskExecutor.invokeAll(+ Collections.singletonList(+ () -> {+ throw new Exception("exc");+ })));assertEquals("exc", runtimeException.getCause().getMessage());}@@ -128,21 +132,18 @@ public class TestTaskExecutor extends LuceneTestCase {return new LeafCollector() {@Overridepublic void setScorer(Scorable scorer) throws IOException {- TaskExecutor.Task<Void> task =- searcher- .getTaskExecutor()- .createTask(+ searcher+ .getTaskExecutor()+ .invokeAll(+ Collections.singletonList(() -> {// make sure that we don't miss disabling concurrency one// level deeper- TaskExecutor.Task<Object> anotherTask =- searcher.getTaskExecutor().createTask(() -> null);searcher.getTaskExecutor()- .invokeAll(Collections.singletonList(anotherTask));+ .invokeAll(Collections.singletonList(() -> null));return null;- });- searcher.getTaskExecutor().invokeAll(Collections.singletonList(task));+ }));}@Override@@ -197,9 +198,9 @@ public class TestTaskExecutor extends LuceneTestCase {// TaskExecutor, the safeguard is shared among all the searchers that get// the same executorIndexSearcher indexSearcher = new IndexSearcher(reader, executorService);- TaskExecutor.Task<Void> task =- indexSearcher.getTaskExecutor().createTask(() -> null);- searcher.getTaskExecutor().invokeAll(Collections.singletonList(task));+ indexSearcher+ .getTaskExecutor()+ .invokeAll(Collections.singletonList(() -> null));}@Override