From 54ab7407fac6a757c6a8e071e697c9ede0a6a20d Mon Sep 17 00:00:00 2001 From: Zlatin Balevsky Date: Tue, 10 Jul 2018 21:06:05 +0100 Subject: [PATCH] switch to map --- .../com/muwire/hostcache/HostPool.groovy | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/host-cache/src/main/groovy/com/muwire/hostcache/HostPool.groovy b/host-cache/src/main/groovy/com/muwire/hostcache/HostPool.groovy index a9460767..f28f69a1 100644 --- a/host-cache/src/main/groovy/com/muwire/hostcache/HostPool.groovy +++ b/host-cache/src/main/groovy/com/muwire/hostcache/HostPool.groovy @@ -7,8 +7,8 @@ class HostPool { final def maxFailures final def maxAge - def verified = new HashSet() - def unverified = new HashSet() + def verified = new HashMap() + def unverified = new HashMap() HostPool(maxFailures, maxAge) { this.maxAge = maxAge @@ -19,15 +19,15 @@ class HostPool { if (verified.isEmpty()) { return Collections.emptyList() } - def asList = verified.stream().filter({ it -> leaf ? it.leafSlots : it.peerSlots}).collect(Collectors.toList()) + def asList = verified.values().stream().filter({ it -> leaf ? it.leafSlots : it.peerSlots}).collect(Collectors.toList()) Collections.shuffle(asList) return asList[0..Math.min(max, asList.size()) -1] } synchronized def addUnverified(host) { - if (!verified.contains(host)) { - unverified.add(host) + if (!verified.containsKey(host.destination)) { + unverified.put(host.destination, host) } } @@ -35,37 +35,39 @@ class HostPool { if (unverified.isEmpty()) { return Collections.emptyList() } - def asList = unverified.asList() + def asList = unverified.values().asList() Collections.shuffle(asList) return asList[0..(Math.min(max, asList.size())-1)] } synchronized def verify(host) { - if (!unverified.remove(host)) + if (!unverified.remove(host.destination)) throw new IllegalArgumentException() host.verifyTime = System.currentTimeMillis(); host.verificationFailures = 0 - verified.add(host) + verified.put(host.destination, host) } synchronized def fail(host) { - if (!unverified.contains(host)) + if (!unverified.containsKey(host.destination)) throw new IllegalArgumentException() host.verificationFailures++ } synchronized def age() { final long now = System.currentTimeMillis() - for (Iterator iter = verified.iterator(); iter.hasNext();) { - def host = iter.next() + for (Iterator iter = verified.keySet().iterator(); iter.hasNext();) { + def destination = iter.next() + def host = verified.get(destination) if (host.verifyTime + maxAge < now) { iter.remove() - unverified.add(host) + unverified.put(host.destination, host) } } - for (Iterator iter = unverified.iterator(); iter.hasNext();) { - def host = iter.next() + for (Iterator iter = unverified.keySet().iterator(); iter.hasNext();) { + def destination = iter.next() + def host = unverified.get(destination) if (host.verificationFailures >= maxFailures) { iter.remove() }