public class ThrottledByteSource extends Object implements ByteSource
For example:
ByteSource fastSrc = new FileByteSource("/tmp/data.bin"); ByteSource slowSrc = new ThrottledByteSource(fastSrc, 1024, 0, 1024); // 1Kb/s AsyncIterator.forEach( slowSrc::read, System.out::println ).finally_( slowSrc::close );
The throttling is based on a curve b(t). At time t, the total number of bytes served should not exceed b(t).
The unit of t is milli-second. t is relative to the 1st read, i.e. t=0 on the first read() call.
See ThrottledByteSource.Curve
.
The `bufferSize` influences the size and frequency of reads. For example, suppose we throttle a very fast origin source at 10K bytes per second, if bufferSize=10K, read() will stall for 1 second then yield a 10K buffer; if bufferSize=1K, read() will stall for 0.1 second then yield a 1K buffer.
Skipped bytes are not counted as served bytes. The `skip(n)` method of this class is guaranteed to return `n`, so that the skipped bytes will not interfere with the throughput of read().
Modifier and Type | Class and Description |
---|---|
static interface |
ThrottledByteSource.Curve
The curve used in
ThrottledByteSource . |
Constructor and Description |
---|
ThrottledByteSource(ByteSource origin,
int bufferSize,
ThrottledByteSource.Curve curve)
Create a throttled wrapper of the origin source.
|
ThrottledByteSource(ByteSource origin,
int bufferSize,
long b0,
long bytesPerSecond)
Create a throttled wrapper of the origin source, with a linear curve.
|
Instance Methods | |
---|---|
long |
skip(long n)
Skip forward `n` bytes.
|
Async<ByteBuffer> |
read()
Read the next chunk of bytes.
|
Async<Void> |
close()
Close this source.
|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
asString, asString, readAll, toSink
public ThrottledByteSource(ByteSource origin, int bufferSize, ThrottledByteSource.Curve curve)
public ThrottledByteSource(ByteSource origin, int bufferSize, long b0, long bytesPerSecond)
The curve used here is
Curve.linear(b0, bytesPerSecond)
.
public long skip(long n) throws IllegalArgumentException, IllegalStateException
This implementation guarantees that `n` bytes will be skipped, and `n` will be returned (barring any exceptions).
skip
in interface ByteSource
n
- number of bytes to skip; n >= 0
.IllegalStateException
- if this source is closed.IllegalArgumentException
- if n < 0
.public Async<ByteBuffer> read() throws IllegalStateException
Typically an artificial delay will be introduced for the purpose of throttling.
read
in interface ByteSource
IllegalStateException
- if this source is closed.public Async<Void> close()
close
in interface ByteSource