![JAR search and dependency download from the Maven repository](/logo.png)
com.pivovarit.collectors.CompletionOrderSpliterator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of parallel-collectors Show documentation
Show all versions of parallel-collectors Show documentation
Parallel collection processing with customizable thread pools
package com.pivovarit.collectors;
import java.util.List;
import java.util.Spliterator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.Consumer;
/**
* @author Grzegorz Piwowarek
*/
final class CompletionOrderSpliterator implements Spliterator {
private final int initialSize;
private final BlockingQueue> completed = new LinkedBlockingQueue<>();
private int remaining;
CompletionOrderSpliterator(List> futures) {
this.initialSize = futures.size();
this.remaining = initialSize;
futures.forEach(f -> f.whenComplete((t, __) -> completed.add(f)));
}
@Override
public boolean tryAdvance(Consumer super T> action) {
if (remaining > 0) {
nextCompleted().thenAccept(action).join();
return true;
} else {
return false;
}
}
private CompletableFuture nextCompleted() {
remaining--;
try {
return completed.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
@Override
public Spliterator trySplit() {
return null;
}
@Override
public long estimateSize() {
return initialSize;
}
@Override
public int characteristics() {
return SIZED | IMMUTABLE | NONNULL;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy