Created
November 15, 2017 20:47
-
-
Save spullara/9367002b119eeed646706d7484c68330 to your computer and use it in GitHub Desktop.
Read it more slowly so as not to overload the system
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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