commit 1f7f1058d0b283b5ff92218e00caf9030edebe69
parent 945bf27e660d7076705fd532ee5a604f4f7f81d6
Author: Matthias Jaros <jaros@mailbox.org>
Date: Mon, 16 Mar 2026 12:05:35 +0100
- Removed synchronized on PortRange class, because only called from one
thread only.
- Added max virtual thread worker cap to reduce memory consumption if
required. Therefore also moved progress update into virtual thread,
otherwise progress just gets updated at the end of a target host scan.
Diffstat:
2 files changed, 16 insertions(+), 7 deletions(-)
diff --git a/src/main/java/com/it_jaros/networkScanner/PortRange.java b/src/main/java/com/it_jaros/networkScanner/PortRange.java
@@ -65,7 +65,7 @@ public class PortRange {
}
}
- public synchronized int next() {
+ public int next() {
int p = availablePorts.nextSetBit(cursor);
if (p > 0) {
availablePorts.clear(p);
@@ -77,7 +77,7 @@ public class PortRange {
throw new NoSuchElementException("Reached end of port range");
}
- public synchronized boolean hasNext() {
+ public boolean hasNext() {
return availablePorts.nextSetBit(cursor) > 0;
}
diff --git a/src/main/java/com/it_jaros/networkScanner/Scanner.java b/src/main/java/com/it_jaros/networkScanner/Scanner.java
@@ -22,6 +22,7 @@ public class Scanner {
private final Counter counter = new Counter();
private final ProgressBar progressBar = new ProgressBar();
+ private final Semaphore maxWorkers = new Semaphore(100000);
private final Semaphore socketLimit;
private final int timeoutInMillis;
private final long delayInNanos;
@@ -70,10 +71,20 @@ public class Scanner {
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();) {
List<Future<Integer>> futures = new ArrayList<>();
while (portRange.hasNext()) {
+ maxWorkers.acquireUninterruptibly();
final int currentPort = portRange.next();
futures.add(executor.submit(() -> {
- waitForSlot(portSlotFactory);
- return scanPort(target, currentPort);
+ try {
+ waitForSlot(portSlotFactory);
+ int port = scanPort(target, currentPort);
+ if (port != -1) {
+ progress.open().incrementAndGet();
+ }
+ return port;
+ } finally {
+ maxWorkers.release();
+ progress.done().incrementAndGet();
+ }
}));
}
@@ -81,13 +92,11 @@ public class Scanner {
try {
int port = f.get();
if (port != -1) {
+ // openPorts is not threadsafe, so we do not update it outside the worker threads
openPorts.set(port);
- progress.open().incrementAndGet();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
- } finally {
- progress.done().incrementAndGet();
}
});
}