From d9a8311b8e40a0d390a993e409933f8ee737c12e Mon Sep 17 00:00:00 2001 From: PunKeel Date: Sat, 14 May 2016 23:37:12 +0200 Subject: [PATCH] Use expireAfterWrite to perform throttle --- .../java/net/md_5/bungee/ConnectionThrottle.java | 13 +++++-------- .../src/test/java/net/md_5/bungee/ThrottleTest.java | 4 ++-- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/proxy/src/main/java/net/md_5/bungee/ConnectionThrottle.java b/proxy/src/main/java/net/md_5/bungee/ConnectionThrottle.java index a2690b77..207defad 100644 --- a/proxy/src/main/java/net/md_5/bungee/ConnectionThrottle.java +++ b/proxy/src/main/java/net/md_5/bungee/ConnectionThrottle.java @@ -8,25 +8,22 @@ import java.util.concurrent.TimeUnit; public class ConnectionThrottle { - private final int throttleTime; - private final Cache throttle; + private final Cache throttle; public ConnectionThrottle(int throttleTime) { - this.throttleTime = throttleTime; this.throttle = CacheBuilder.newBuilder() .concurrencyLevel( Runtime.getRuntime().availableProcessors() ) .initialCapacity( 100 ) - .expireAfterAccess( throttleTime, TimeUnit.MILLISECONDS ) + .expireAfterWrite( throttleTime, TimeUnit.MILLISECONDS ) .build(); } public boolean throttle(InetAddress address) { - Long value = throttle.getIfPresent( address ); - long currentTime = System.currentTimeMillis(); + boolean isThrottled = throttle.getIfPresent( address ); + throttle.put( address, true ); - throttle.put( address, currentTime ); - return value != null && currentTime - value < throttleTime; + return isThrottled; } } diff --git a/proxy/src/test/java/net/md_5/bungee/ThrottleTest.java b/proxy/src/test/java/net/md_5/bungee/ThrottleTest.java index cedd38ce..5f501f7d 100644 --- a/proxy/src/test/java/net/md_5/bungee/ThrottleTest.java +++ b/proxy/src/test/java/net/md_5/bungee/ThrottleTest.java @@ -11,7 +11,7 @@ public class ThrottleTest @Test public void testThrottle() throws InterruptedException, UnknownHostException { - ConnectionThrottle throttle = new ConnectionThrottle( 5 ); + ConnectionThrottle throttle = new ConnectionThrottle( 10 ); InetAddress address; try @@ -25,7 +25,7 @@ public class ThrottleTest Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); Assert.assertTrue( "Address should be throttled", throttle.throttle( address ) ); - Thread.sleep( 15 ); + Thread.sleep( 50 ); Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); } }