com.limegroup.gnutella.util
Class BandwidthThrottle

java.lang.Object
  extended bycom.limegroup.gnutella.util.BandwidthThrottle

public class BandwidthThrottle
extends java.lang.Object

Limits throughput of a stream to at most N bytes per T seconds. Mutable and thread-safe.

In the following example, throttle is used to send the contents of buf to out at no more than N/T bytes per second:

      BandwidthThrottle throttle=new BandwidthThrottle(N, T);
      OutputStream out=...;
      byte[] buf=...;
      for (int i=0; i

 This class works by allowing exactly N bytes to be sent every T seconds.  If
 the number of bytes for a given window have been exceeded, subsequent calls
 to request(..) will block.  The default value of T is 100 milliseconds.
 Smaller window values T allow fairer bandwidth sharing and less noticeable
 pauses but may decrease efficiency slightly.

Note that throttles are not cumulative. In the future, this may allow enable fancier control. Also, BandwidthThrottle may be able delegate to other throttles. This would allow, for example, a 15 KB/s Gnutella messaging throttle, with no more than 10 KB/s devoted to uploads.

This implementation is based on the Bandwidth class from the Freenet project. It has been simplified and better documented.


Constructor Summary
BandwidthThrottle(float bytesPerSecond)
          Creates a new bandwidth throttle at the given throttle rate.
 
Method Summary
 int request(int desired)
          Blocks until the caller can send at least one byte without violating bandwidth constraints.
 void setRate(float bytesPerSecond)
          Sets the throttle to the given throttle rate.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

BandwidthThrottle

public BandwidthThrottle(float bytesPerSecond)
Creates a new bandwidth throttle at the given throttle rate. The default windows size T is used. The bytes per windows N is calculated from bytesPerSecond.

Parameters:
bytesPerSecond - the limits in bytes (not bits!) per second (not milliseconds!)
Method Detail

setRate

public void setRate(float bytesPerSecond)
Sets the throttle to the given throttle rate. The default windows size T is used. The bytes per windows N is calculated from bytesPerSecond.

Parameters:
bytesPerSecond - the limits in bytes (not bits!) per second (not milliseconds!)

request

public int request(int desired)
Blocks until the caller can send at least one byte without violating bandwidth constraints. Records the number of byte sent.

Parameters:
desired - the number of bytes the caller would like to send
Returns:
the number of bytes the sender is expected to send, which is always greater than one and less than or equal to desired