Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Read it more slowly so as not to overload the system
public class SlowInputStream extends BufferedInputStream {
private final long start;
private final double rate;
private long read;
@Override
public synchronized int read(byte[] b, int off, int len) throws IOException {
maybeWait();
int bytes = super.read(b, off, len);
read += bytes;
return bytes;
}
@Override
public synchronized int read() throws IOException {
maybeWait();
read++;
return super.read();
}
private void maybeWait() {
double millis = read / rate - (System.currentTimeMillis() - start);
if (millis > 0) {
try {
Thread.sleep((long) millis);
} catch (InterruptedException e) {
// Continue
}
}
}
public SlowInputStream(InputStream in, long length, int time, TimeUnit timeUnit) {
super(in);
rate = ((double) length) / timeUnit.toMillis(time);
start = System.currentTimeMillis();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.