UniquePortSupplier { public synchronized int getAvailablePort() { int result = IntStream.generate(supplier) .filter(port -> !usedPorts.contains(port)) .findFirst() .getAsInt(); usedPorts.add(result); return result; } UniquePortSupplier();  UniquePortSupplier(IntSupplier supplier); synchronized int getAvailablePort();  }
@Test public void returnsUniquePorts() { PrimitiveIterator.OfInt iterator = IntStream.of(0, 0, 0, 0, 0, 1).iterator(); UniquePortSupplier supplier = new UniquePortSupplier(iterator::nextInt); int port0 = supplier.getAvailablePort(); int port1 = supplier.getAvailablePort(); assertThat(port0).isEqualTo(0); assertThat(port1).isEqualTo(1); }
@Test public void getsPortsFromProvidedSupplier() { int expectedPort = 555; UniquePortSupplier supplier = new UniquePortSupplier(() -> expectedPort); int port = supplier.getAvailablePort(); assertThat(port).isEqualTo(expectedPort); }