diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/tasks/PersistBlockTask.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/tasks/PersistBlockTask.java index 4d007e1927..31800c03f2 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/tasks/PersistBlockTask.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/tasks/PersistBlockTask.java @@ -27,6 +27,7 @@ import org.hyperledger.besu.ethereum.mainnet.ProtocolSpec; import org.hyperledger.besu.plugin.services.MetricsSystem; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; @@ -67,22 +68,20 @@ public class PersistBlockTask extends AbstractEthTask { final List blocks, final HeaderValidationMode headerValidationMode, final MetricsSystem metricsSystem) { - checkArgument(blocks.size() > 0); + checkArgument(!blocks.isEmpty(), "No blocks to import provided"); return () -> { final List successfulImports = new ArrayList<>(); - CompletableFuture future = null; - for (final Block block : blocks) { - if (future == null) { - future = - importBlockAndAddToList( - protocolSchedule, - protocolContext, - block, - successfulImports, - headerValidationMode, - metricsSystem); - continue; - } + final Iterator blockIterator = blocks.iterator(); + CompletableFuture future = + importBlockAndAddToList( + protocolSchedule, + protocolContext, + blockIterator.next(), + successfulImports, + headerValidationMode, + metricsSystem); + while (blockIterator.hasNext()) { + final Block block = blockIterator.next(); future = future.thenCompose( b -> @@ -122,34 +121,34 @@ public class PersistBlockTask extends AbstractEthTask { final List blocks, final HeaderValidationMode headerValidationMode, final MetricsSystem metricsSystem) { - checkArgument(blocks.size() > 0); + checkArgument(!blocks.isEmpty(), "No blocks to import provided"); return () -> { final CompletableFuture> finalResult = new CompletableFuture<>(); final List successfulImports = new ArrayList<>(); - CompletableFuture future = null; - for (final Block block : blocks) { - if (future == null) { - future = - PersistBlockTask.create( - protocolSchedule, protocolContext, block, headerValidationMode, metricsSystem) - .run(); - continue; - } + final Iterator> tasks = + blocks.stream() + .map( + block -> + PersistBlockTask.create( + protocolSchedule, + protocolContext, + block, + headerValidationMode, + metricsSystem)) + .iterator(); + + CompletableFuture future = tasks.next().run(); + while (tasks.hasNext()) { + final PersistBlockTask task = tasks.next(); future = future .handle((r, t) -> r) .thenCompose( - (r) -> { + r -> { if (r != null) { successfulImports.add(r); } - return PersistBlockTask.create( - protocolSchedule, - protocolContext, - block, - headerValidationMode, - metricsSystem) - .run(); + return task.run(); }); } future.whenComplete(