changeset 998:3f116e71c1cd

PortPool
author Devel 2
date Mon, 30 Sep 2019 13:52:19 +0200
parents c43894f26e50
children e176852a95f6
files stress-tester/src/main/java/com/passus/st/emitter/PortPool.java stress-tester/src/main/java/com/passus/st/emitter/PortPoolImpl.java stress-tester/src/main/java/com/passus/st/emitter/SynchronizedPortPoolWrapper.java
diffstat 3 files changed, 96 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stress-tester/src/main/java/com/passus/st/emitter/PortPool.java	Mon Sep 30 13:52:19 2019 +0200
@@ -0,0 +1,9 @@
+package com.passus.st.emitter;
+
+public interface PortPool {
+
+    int borrow();
+
+    void release(int port);
+    
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stress-tester/src/main/java/com/passus/st/emitter/PortPoolImpl.java	Mon Sep 30 13:52:19 2019 +0200
@@ -0,0 +1,63 @@
+package com.passus.st.emitter;
+
+import com.passus.commons.collection.bitmap.BitMapInt;
+import com.passus.net.PortRange;
+
+public class PortPoolImpl implements PortPool {
+
+    private final int minPort;
+
+    private final int maxPort;
+
+    private final BitMapInt borrowMap;
+
+    private int free;
+
+    private int currentPort;
+
+    public PortPoolImpl() {
+        this(1024, PortRange.MAX_VALUE);
+    }
+
+    public PortPoolImpl(int minPort, int maxPort) {
+        if (minPort >= maxPort) {
+            throw new IllegalArgumentException("maxPort <= minPort");
+        }
+
+        this.currentPort = minPort;
+        this.minPort = minPort;
+        this.maxPort = maxPort;
+        borrowMap = BitMapInt.create(maxPort);
+        free = maxPort - minPort + 1;
+    }
+
+    public int getFree() {
+        return free;
+    }
+
+    @Override
+    public int borrow() {
+        if (free == 0) {
+            return -1;
+        }
+
+        while (borrowMap.isset(currentPort)) {
+            currentPort++;
+            if (currentPort > maxPort) {
+                currentPort = minPort;
+            }
+        }
+
+        borrowMap.set(currentPort);
+        free--;
+        return currentPort;
+    }
+
+    @Override
+    public void release(int port) {
+        if (borrowMap.isset(port)) {
+            borrowMap.unset(port);
+            free++;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/stress-tester/src/main/java/com/passus/st/emitter/SynchronizedPortPoolWrapper.java	Mon Sep 30 13:52:19 2019 +0200
@@ -0,0 +1,24 @@
+package com.passus.st.emitter;
+
+public class SynchronizedPortPoolWrapper implements PortPool {
+
+    private final PortPool portPool;
+
+    public SynchronizedPortPoolWrapper(PortPool portPool) {
+        this.portPool = portPool;
+    }
+
+    @Override
+    public int borrow() {
+        synchronized (this) {
+            return portPool.borrow();
+        }
+    }
+
+    @Override
+    public void release(int port) {
+        synchronized (this) {
+            portPool.release(port);
+        }
+    }
+}