From 8abc5f6d209778b678fb882b1213f596dfb42f7b Mon Sep 17 00:00:00 2001 From: Matthias Jaros Date: Thu, 20 Aug 2026 17:14:51 +0200 Subject: Refactored consumer into custom method --- src/main/java/com/it_jaros/jns/scan/Scanner.java | 50 ++++++++++++++++-------- 1 file changed, 33 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/main/java/com/it_jaros/jns/scan/Scanner.java b/src/main/java/com/it_jaros/jns/scan/Scanner.java index 9a62d52..3e84a26 100644 --- a/src/main/java/com/it_jaros/jns/scan/Scanner.java +++ b/src/main/java/com/it_jaros/jns/scan/Scanner.java @@ -45,25 +45,30 @@ public class Scanner implements AutoCloseable { host -> new ScanHostTask(host, context) ); - // the main thread is the consumer - // Let the consumer run as long as the producer runs - // or if still tasks are pending in pipeline - // we do not listen to canceled here because we want - // all results (also partial) collected for the consumer - // with whatever is there already + try { + runConsumerLoop(state, consumer); + } finally { + scan.stop(); + } + } + + /** + * the main thread is the consumer + * Let the consumer run as long as the producer runs + * or if still tasks are pending in pipeline + * we do not listen to canceled here because we want + * all results (also partial) collected for the consumer + * with whatever is there already + */ + private void runConsumerLoop(ProducerState state, Consumer consumer) { while (state.running().get() || state.inPipeline().get() > 0) { - try { - PollState poll = getHostResult(state); - if (poll instanceof PollState.Success(ScanResult value)) { - consumer.accept(value); - } else if (poll instanceof PollState.Failure(Throwable error)) { - mapToScanResult(error).ifPresent(consumer); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); + PollState poll = getPollStateOfScanResult(state); + if (poll instanceof PollState.Success(ScanResult value)) { + consumer.accept(value); + } else if (poll instanceof PollState.Failure(Throwable error)) { + mapToScanResult(error).ifPresent(consumer); } } - scan.stop(); } private Optional mapToScanResult(Throwable error) { @@ -87,8 +92,19 @@ public class Scanner implements AutoCloseable { return Optional.of(ScanResult.from(error)); } - private PollState getHostResult(ProducerState state) throws InterruptedException { + private PollState getPollStateOfScanResult(ProducerState state) { + try { + return pollCompletedHost(state); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + + return new PollState.Unavailable<>(); + } + + private static PollState pollCompletedHost(ProducerState state) throws InterruptedException { Future finishedHost = state.completionService().poll(ProducerThread.pollInterval.toMillis(), TimeUnit.MILLISECONDS); + if (finishedHost == null) { return new PollState.Unavailable<>(); } -- cgit v1.3.1