Use expireAfterWrite to perform throttle
This commit is contained in:
parent
d14b96d55e
commit
d9a8311b8e
@ -8,25 +8,22 @@ import java.util.concurrent.TimeUnit;
|
|||||||
public class ConnectionThrottle
|
public class ConnectionThrottle
|
||||||
{
|
{
|
||||||
|
|
||||||
private final int throttleTime;
|
private final Cache<InetAddress, Boolean> throttle;
|
||||||
private final Cache<InetAddress, Long> throttle;
|
|
||||||
|
|
||||||
public ConnectionThrottle(int throttleTime)
|
public ConnectionThrottle(int throttleTime)
|
||||||
{
|
{
|
||||||
this.throttleTime = throttleTime;
|
|
||||||
this.throttle = CacheBuilder.newBuilder()
|
this.throttle = CacheBuilder.newBuilder()
|
||||||
.concurrencyLevel( Runtime.getRuntime().availableProcessors() )
|
.concurrencyLevel( Runtime.getRuntime().availableProcessors() )
|
||||||
.initialCapacity( 100 )
|
.initialCapacity( 100 )
|
||||||
.expireAfterAccess( throttleTime, TimeUnit.MILLISECONDS )
|
.expireAfterWrite( throttleTime, TimeUnit.MILLISECONDS )
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean throttle(InetAddress address)
|
public boolean throttle(InetAddress address)
|
||||||
{
|
{
|
||||||
Long value = throttle.getIfPresent( address );
|
boolean isThrottled = throttle.getIfPresent( address );
|
||||||
long currentTime = System.currentTimeMillis();
|
throttle.put( address, true );
|
||||||
|
|
||||||
throttle.put( address, currentTime );
|
return isThrottled;
|
||||||
return value != null && currentTime - value < throttleTime;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,7 @@ public class ThrottleTest
|
|||||||
@Test
|
@Test
|
||||||
public void testThrottle() throws InterruptedException, UnknownHostException
|
public void testThrottle() throws InterruptedException, UnknownHostException
|
||||||
{
|
{
|
||||||
ConnectionThrottle throttle = new ConnectionThrottle( 5 );
|
ConnectionThrottle throttle = new ConnectionThrottle( 10 );
|
||||||
InetAddress address;
|
InetAddress address;
|
||||||
|
|
||||||
try
|
try
|
||||||
@ -25,7 +25,7 @@ public class ThrottleTest
|
|||||||
Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) );
|
Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) );
|
||||||
Assert.assertTrue( "Address should 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 ) );
|
Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) );
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user