Limiting download speed using Java

I will answer in a general way, without referring specifically to Java.

A common technique to throttle a connection is to wait after having read from the open socket. Your code can do a bit of logic to count how fast it has been downloading. There are many ways of accomplishing this and what you intend to do with this will influence how you do it.

In Python-like pseudocode:

data_per_timeslot = 500 * 1000 # 500 KB/s
timeslot = 1000 * 1000 # 1 sec (in us)

with new_connection() as conn:
    download_complete = False
    chunk_size = data_per_sec

    ts = nil

    while not download_complete:
        ts = time()
        buffer = conn.read(chunk_size)
        diff = time() - ts

        # do something with data
        data.append(buffer) 

        # sleep if there is still time left in our timeslot,
        # to throttle the connection a bit
        if diff < timeslot: 
            usleep(timeslot - diff)

If you need throttling to remove excessive strain on a server, it makes sense to give a little boost to the user if the connection speed dipped during the last few seconds. Say I am downloading at 500 KB/s (throttled); I load a page in my browser and the download goes down at 250 KB/s for a few seconds; the client should be allowed to “catch up” by raising the download speed in bursts of a few hundreds of KB/s.

However, if you need throttling in the context of a video conference app or similar, it will not make sense to boost the transfer speed after it sagged since there is no data to “catch up” to; in realtime video, you drop missing frames instead.

Leave a Comment