Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's no elegant way to do this.</p> <p>A simple but inelegant way would be to write a Java stream wrapper that limits the rate at which bytes are read from the wrapped Stream. For instance, if you wanted to limit to 1000 bytes per second, the <code>int read()</code> method could be implemented as follows:</p> <pre><code>Stream in; long timestamp = System.currentTimeInMillis(); int counter = 0; int INTERVAL = 1000; // one second int LIMIT = 1000; // bytes per INTERVAL ... /** * Read one byte with rate limiting */ @Override public int read() { if (counter &gt; LIMIT) { long now = System.currentTimeInMillis(); if (timestamp + INTERVAL &gt;= now) { Thread.sleep(timestamp + INTERVAL - now); } timestamp = now; counter = 0; } int res = in.read(); if (res &gt;= 0) { counter++; } return res; } </code></pre> <hr> <p>It is worth noting that throttling rates like this can have negative as well as positive effects. On the negative side: </p> <ul> <li><p>It ties down resources on the server side for longer. In this case, we are talking about the Java thread that is handling the download, and memory in kernel space is used to buffer received network packets until the application reads them.</p></li> <li><p>It may also lead to <em>more</em> network traffic. The problem is that this kind of throttling will disrupt the smooth flow of packets. The server will only buffer a relatively small number of packets, and when that number is exceeded, it has to tell the client to STOP for now. This requires extra signalling packets (ACKs) and there will probably be data packets dropped in the process. Eventually, those data packets will need to be retransmitted.</p></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload