Skip to content

Instantly share code, notes, and snippets.

@spullara
Created November 15, 2017 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spullara/9367002b119eeed646706d7484c68330 to your computer and use it in GitHub Desktop.
Save spullara/9367002b119eeed646706d7484c68330 to your computer and use it in GitHub Desktop.
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